Singly Linked List in C
A singly linked list is a chain of nodes. Each node holds a value and a pointer to the next node; the last node points to NULL. Unlike an array, the list can grow and shrink while the program runs, and inserting at the front takes just a couple of pointer changes.
In this lesson you will write a complete singly linked list in C: create a node, insert at the beginning, at the end and at a position, delete by value, search, count, display, reverse and free the whole list.
What You Will Learn
- The structure of a node and the role of the head pointer.
- How to insert a node at the beginning, end and a given position.
- How to delete a node by value.
- How to traverse, search and count nodes.
- How to reverse a linked list in place.
- Why you pass
struct node **headto functions that change the head.
Singly Linked List in C Explained
Exam definition: A singly linked list is a linear data structure made of nodes, where each node contains a data field and a next pointer to the following node. A pointer called head stores the address of the first node, and the next pointer of the last node is NULL. Nodes are created dynamically, so the list can change size at run time, but elements can only be reached sequentially from the head.
Memory trick: A singly linked list is a treasure hunt. Each clue (node) has a prize (data) and tells you where the next clue is (next). The first clue's location is written on your hand (head). The last clue says "the end" (NULL). You can't jump to clue 5; you must follow clues 1, 2, 3, 4.
head
│
▼
┌──────┬───┐ ┌──────┬───┐ ┌──────┬──────┐
│ 10 │ ●─┼──►│ 20 │ ●─┼──►│ 30 │ NULL │
└──────┴───┘ └──────┴───┘ └──────┴──────┘
data next data next data next
Syntax of a Node and Basic Operations
struct node
{
int data;
struct node *next;
};
struct node *head = NULL; /* empty list */
/* insert at beginning */
new_node->next = head;
head = new_node;
/* traverse */
for (p = head; p != NULL; p = p->next)
printf("%d ", p->data);
| Operation | Time | Why |
|---|---|---|
| Insert at beginning | O(1) | Only head changes |
| Insert at end | O(n) | Must walk to the last node (O(1) with a tail pointer) |
| Insert at position k | O(n) | Walk to node k − 1 |
| Delete by value | O(n) | Search first, then relink |
| Search / count / display | O(n) | Visit every node |
Example 1: Singly Linked List Operations
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *create_node(int value)
{
struct node *n = malloc(sizeof *n);
if (n == NULL)
{
printf("Out of memory\n");
exit(1);
}
n->data = value;
n->next = NULL;
return n;
}
void insert_begin(struct node **head, int value)
{
struct node *n = create_node(value);
n->next = *head;
*head = n;
}
void insert_end(struct node **head, int value)
{
struct node *n = create_node(value), *p;
if (*head == NULL)
{
*head = n;
return;
}
for (p = *head; p->next != NULL; p = p->next)
;
p->next = n;
}
/* position starts at 1 */
void insert_at(struct node **head, int pos, int value)
{
struct node *n, *p = *head;
int i;
if (pos == 1)
{
insert_begin(head, value);
return;
}
for (i = 1; i < pos - 1 && p != NULL; i++)
p = p->next;
if (p == NULL)
{
printf("Position %d is invalid\n", pos);
return;
}
n = create_node(value);
n->next = p->next;
p->next = n;
}
int delete_value(struct node **head, int value)
{
struct node *p = *head, *prev = NULL;
while (p != NULL && p->data != value)
{
prev = p;
p = p->next;
}
if (p == NULL)
return 0; /* not found */
if (prev == NULL)
*head = p->next; /* deleting the first node */
else
prev->next = p->next;
free(p);
return 1;
}
int search(struct node *head, int value)
{
int pos = 1;
for (; head != NULL; head = head->next, pos++)
if (head->data == value)
return pos;
return -1;
}
void display(struct node *head)
{
for (; head != NULL; head = head->next)
printf("%d -> ", head->data);
printf("NULL\n");
}
void free_list(struct node **head)
{
struct node *next;
while (*head != NULL)
{
next = (*head)->next;
free(*head);
*head = next;
}
}
int main(void)
{
struct node *head = NULL;
insert_end(&head, 20);
insert_end(&head, 30);
insert_begin(&head, 10);
insert_end(&head, 50);
printf("List : ");
display(head);
insert_at(&head, 4, 40);
printf("Insert 40 at 4: ");
display(head);
printf("Search 30 : position %d\n", search(head, 30));
printf("Search 99 : position %d\n", search(head, 99));
delete_value(&head, 10);
printf("Delete 10 : ");
display(head);
delete_value(&head, 40);
printf("Delete 40 : ");
display(head);
printf("Delete 99 : %s\n", delete_value(&head, 99) ? "deleted" : "not found");
free_list(&head);
printf("After free : ");
display(head);
return 0;
}
Output
List : 10 -> 20 -> 30 -> 50 -> NULL Insert 40 at 4: 10 -> 20 -> 30 -> 40 -> 50 -> NULL Search 30 : position 3 Search 99 : position -1 Delete 10 : 20 -> 30 -> 40 -> 50 -> NULL Delete 40 : 20 -> 30 -> 50 -> NULL Delete 99 : not found After free : NULL
Code Explanation
create_nodeallocates a node withmalloc, fillsdata, setsnext = NULLand checks for out-of-memory.- Functions that may change the first node (insert_begin, insert_at, delete_value, free_list) receive
struct node **head, the address of main's head pointer, so they can update it. With a plainstruct node *headthey would only change a copy. insert_endwalks untilp->next == NULL(the last node) and links the new node there.insert_at(&head, 4, 40)walks to node 3 (value 30), then setsnew->next = 30's next(50) and30's next = new. The order matters: link the new node first, then change the old link.delete_valuekeeps aprevpointer. To remove a node, it makesprev->nextskip over it, then frees it. Deleting the head just movesheadforward.free_listsavesnextbefore freeing each node, because a freed node must never be read again.
How Insertion and Deletion Work
INSERT 40 after 30 DELETE 10 (the head)
before: 30 ──► 50 before: head ──► 10 ──► 20
step 1: new(40).next = 30.next step 1: p = head (10)
30 ──► 50 step 2: head = p.next
40 ──► 50 head ──► 20
step 2: 30.next = new step 3: free(p)
30 ──► 40 ──► 50
DELETE 40 (middle): prev(30).next = 40.next -> 30 ──► 50, then free(40)
Rule: never lose the rest of the list. Always connect the new or bypassing link before you overwrite or free anything.
Example 2: Reverse a Linked List
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void push(struct node **head, int value)
{
struct node *n = malloc(sizeof *n);
if (n == NULL)
exit(1);
n->data = value;
n->next = *head;
*head = n;
}
void reverse(struct node **head)
{
struct node *prev = NULL, *curr = *head, *next;
while (curr != NULL)
{
next = curr->next; /* 1. remember the rest */
curr->next = prev; /* 2. turn the arrow back */
prev = curr; /* 3. move prev forward */
curr = next; /* 4. move curr forward */
}
*head = prev;
}
void display(const struct node *p)
{
for (; p != NULL; p = p->next)
printf("%d ", p->data);
printf("\n");
}
int main(void)
{
struct node *head = NULL, *tmp;
int i;
for (i = 5; i >= 1; i--)
push(&head, i); /* list: 1 2 3 4 5 */
printf("Original: ");
display(head);
reverse(&head);
printf("Reversed: ");
display(head);
while (head != NULL)
{
tmp = head->next;
free(head);
head = tmp;
}
return 0;
}
Output
Original: 1 2 3 4 5 Reversed: 5 4 3 2 1
- The reverse uses three pointers:
prev,currandnext. Each loop turns one arrow around. - It works in place: no new nodes, O(n) time and O(1) extra memory. This is one of the most asked linked-list interview questions.
- When the loop ends,
prevpoints to the old last node, which becomes the new head.
Important Points to Remember
- A node = data + next; the last node's next is NULL; head points to the first node.
- An empty list has
head == NULL; always handle this case. - Pass struct node **head when a function may change the first node.
- When inserting: set the new node's next first, then change the old link.
- When deleting: bypass the node, then free it.
- Free every node when done; save
nextbefore calling free.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Passing head instead of &head | Insert at beginning seems to do nothing | Use struct node **head |
p->next = n; n->next = p->next; | n points to itself; the rest of the list is lost | Set n->next first |
Using a node after free | Undefined behavior, random crashes | Save next before freeing |
Not checking head == NULL | Crash on an empty list | Handle the empty case first |
Loop condition p->next != NULL when visiting all nodes | Skips the last node | Use p != NULL to visit every node |
Singly Linked List Practice Questions
- What is a singly linked list? Draw a list of three nodes.
- Why is insertion at the beginning O(1)?
- Why do some functions take
struct node **head? - Write the steps to delete a middle node.
- How does the iterative reverse algorithm work?
Show answers
- A chain of nodes, each holding data and a pointer to the next node, starting from head and ending with NULL: head → [10|●] → [20|●] → [30|NULL].
- Only two pointer assignments are needed (new→next = head; head = new), whatever the list length.
- So they can change main's head pointer (for example when inserting or deleting the first node).
- Find the node and keep a pointer to the previous node; set prev→next = node→next; free(node).
- It walks the list with prev, curr and next, turning each curr→next to point to prev, then moves forward; at the end, head = prev.
Coding Exercise
Write a function int middle(struct node *head) that returns the middle element using the slow and fast pointer method (slow moves 1 step, fast moves 2). Test it on 10 → 20 → 30 → 40 → 50 and on 10 → 20 → 30 → 40 (return the second middle).
Show solution
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void push(struct node **head, int value)
{
struct node *n = malloc(sizeof *n);
if (n == NULL)
exit(1);
n->data = value;
n->next = *head;
*head = n;
}
int middle(struct node *head)
{
struct node *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
return slow->data;
}
void free_list(struct node *head)
{
struct node *t;
while (head != NULL)
{
t = head->next;
free(head);
head = t;
}
}
int main(void)
{
struct node *a = NULL, *b = NULL;
int i;
for (i = 50; i >= 10; i -= 10)
push(&a, i); /* 10 20 30 40 50 */
for (i = 40; i >= 10; i -= 10)
push(&b, i); /* 10 20 30 40 */
printf("Middle of 5 nodes: %d\n", middle(a));
printf("Middle of 4 nodes: %d\n", middle(b));
free_list(a);
free_list(b);
return 0;
}
Middle of 5 nodes: 30 Middle of 4 nodes: 30
For 4 nodes, the two middles are 20 and 30; this method returns the second one, 30.
Quick Quiz: Singly Linked List (MCQ)
-
The next pointer of the last node is:
A) head B) NULL C) The first node D) Garbage
-
Inserting at the beginning of a singly linked list takes:
A) O(1) B) O(n) C) O(log n) D) O(n²)
-
Accessing the k-th node requires:
A) Direct indexing B) Following links from head C) Binary search D) Hashing
-
To delete a middle node you need a pointer to:
A) Only the node B) The previous node C) The last node D) Nothing
-
Reversing a linked list iteratively uses how many pointers?
A) 1 B) 2 C) 3 D) 5
Show answers
- B: NULL.
- A: O(1).
- B: following links from head.
- B: the previous node.
- C: 3 (prev, curr, next).
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Node | data + next pointer |
|---|---|
| head / last node | First node's address / next = NULL |
| Insert at front | O(1): new→next = head; head = new |
| Access / search | O(n), sequential only |
| Delete | prev→next = node→next, then free |
| Changing head | Pass struct node ** |
| Reverse | prev, curr, next; O(n), O(1) space |
Frequently asked questions
- What is a singly linked list?
- A linear structure of nodes, each with data and a next pointer, starting at head and ending at NULL.
- What are the advantages of a linked list over an array?
- Dynamic size and fast insertion/deletion without shifting elements.
- How do you reverse a linked list?
- Walk the list with prev, curr and next, pointing each node back to prev; finally set head = prev.
Remember
- Linked list = treasure hunt: follow the clues from head to NULL.
- Link first, then break; save next before free.
Next Topic
Next lesson: Doubly Linked List in C. You will add a prev pointer to each node and traverse the list in both directions.