C Linked List — Singly Linked List Implementation
Learning Objectives
- Model data as nodes connected by pointers
- Insert nodes at the front and back of a list
- Traverse and search a linked list safely
- Delete nodes without leaking memory
Why Linked Lists
Arrays store elements in one contiguous block, which makes indexed access fast but makes growth and middle insertions awkward. A linked list stores each element in its own node. Each node holds data and a pointer to the next node, so the list can grow and shrink by linking and unlinking nodes instead of moving big blocks of memory.
The trade-off is that you cannot jump to an arbitrary index instantly. You must walk the chain from the head, which makes operations proportional to the list length.
Node Definition
The building block is a structure with a data field and a next pointer. The final node points to null to mark the end of the chain.
#include
#include
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createNode(int value) {
Node *node = malloc(sizeof(Node));
if (node == NULL) {
return NULL;
}
node->data = value;
node->next = NULL;
return node;
}
Using typedef makes later declarations shorter. Always check that malloc succeeded before writing through the new pointer.
Inserting at the Front
Front insertion is the simplest growth operation. The new node points at the current head, and the head pointer updates to the new node. No loop is required, so the cost stays constant.
void pushFront(Node **head, int value) {
Node *node = createNode(value);
if (node == NULL) {
return;
}
node->next = *head;
*head = node;
}
Passing a pointer to the head pointer lets the function update the caller's head variable. Forgetting that double indirection is one of the most common linked list bugs for beginners.
Traversal and Search
Traversal starts at the head and follows next pointers until null. Search is the same walk with a comparison at each node. Both operations must advance the cursor or the loop will never finish.
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int findValue(Node *head, int target) {
Node *current = head;
while (current != NULL) {
if (current->data == target) {
return 1;
}
current = current->next;
}
return 0;
}
| Operation | Time Cost |
|---|---|
| Insert at front | Constant |
| Search or print | Linear in list length |
| Delete given node pointer | Constant |
| Find then delete | Linear search plus unlink |
Inserting at the Tail
To append, walk to the last node whose next pointer is null, then attach the new node. If the list is empty, the new node becomes the head. This operation is linear because the end is not directly known without a tail pointer.
void pushBack(Node **head, int value) {
Node *node = createNode(value);
if (node == NULL) {
return;
}
if (*head == NULL) {
*head = node;
return;
}
Node *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
}
Programs that append frequently can keep an extra tail pointer to make this constant time, at the cost of maintaining two pointers on every structural change.
Deleting and Freeing
Removing a node means relinking the previous node around it, then freeing the removed node. Clearing an entire list requires a temporary cursor so freeing the current node does not lose the rest of the chain.
void freeList(Node **head) {
Node *current = *head;
while (current != NULL) {
Node *next = current->next;
free(current);
current = next;
}
*head = NULL;
}
⚠️Free Every Node
Each successful malloc needs a matching free. Walking and freeing in one pass with a saved next pointer avoids losing access to the remaining nodes.
Key Takeaways
💡
- Linked list nodes pair data with a pointer to the next node
- Head insertion is constant time; tail insertion needs a full walk
- Pass a pointer to the head pointer when the head itself may change
- Traversal must always advance the cursor to reach the end
- Free every node exactly once when the list is discarded
Practice Questions
- Why does pushFront take a Node pointer to pointer argument?
- What is the time cost of searching a linked list of n nodes?
- How do you safely free an entire linked list without leaking nodes?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions