Programming & DSA
Linked Lists
Linked-list questions are pointer-surgery puzzles: draw boxes and arrows, update pointers in the right order, and count the cost of each operation.
GATE CSE linked lists in C — singly, doubly, and circular lists, insertion and deletion, reversal, middle and cycle detection, and comparison with arrays, with samples and drills.
Learning outcomes
- Write and trace insertion, deletion, and traversal on singly linked lists, including head and tail edge cases
- Reverse a list and find its middle node using pointer techniques in O(n) time and O(1) extra space
- Compare singly, doubly, and circular lists and state the complexity of each operation
- Contrast linked lists with arrays on access, insertion, memory, and locality
Nodes and singly linked lists
- A node holds data and a pointer to the next node: struct node { int data; struct node *next; }; The list is reached through a head pointer; the last node has next = NULL. An empty list has head = NULL.
- Traversal visits nodes one by one with a loop while (p != NULL) p = p->next; it costs O(n). There is no random access: reaching the k-th node costs O(k).
- Insert at head: new->next = head; head = new; — O(1). The order matters: if you set head = new first you lose the old list.
- Insert after a given node p: new->next = p->next; p->next = new; — O(1). Insert at the tail with only a head pointer is O(n) (walk to the end); with a tail pointer it is O(1).
- Delete the head: head = head->next (free the old head) — O(1). Delete a node when you hold a pointer to its predecessor: prev->next = prev->next->next — O(1). Delete the last node needs the second-last node, so it is O(n) in a singly list.
- Search is O(n) even in a sorted list, because binary search needs random access.
- Memory per node = data + pointer. Nodes are allocated individually on the heap, so there is no wasted capacity and no resizing, but extra pointer overhead and poor cache locality.
| Operation (singly, head only) | Cost |
|---|---|
| Insert at head | O(1) |
| Insert at tail | O(n) |
| Delete head | O(1) |
| Delete last node | O(n) |
| Search / access k-th | O(n) / O(k) |
| Insert or delete after a given node pointer | O(1) |
Worked example
Problem. Insert node n after the node p in a singly list. Which two assignments, in which order, are correct?
Solution. First n->next = p->next, then p->next = n. Reversing the order loses the rest of the list (n would point to itself).
Insertion, deletion, and edge cases in C
- Always handle three cases: empty list (head == NULL), operation at the head, and operation at the tail. Most pointer bugs come from forgetting one of them.
- Pointer-to-pointer technique: void insertHead(struct node **head, int x) lets the function change the caller head pointer, because C is pass-by-value. Passing struct node *head alone would modify only a local copy of the head.
- Delete by value: keep a prev pointer; if the match is the head, update head; else prev->next = cur->next; then free(cur).
- Length of a list: iterative loop O(n) time and O(1) space; recursive len(h) = h ? 1 + len(h->next) : 0 takes O(n) time and O(n) stack space.
- Insert into a sorted list: walk while cur->next != NULL && cur->next->data < x, then link — O(n).
- Merging two sorted lists of lengths m and n by relinking nodes takes O(m + n) time and O(1) extra space.
- Printing in reverse with recursion: void rev(struct node *h) { if (h == NULL) return; rev(h->next); printf(h->data); } prints the last node first.
Formulas to remember
-
Insert head: new->next = head; head = new; -
Insert after p: new->next = p->next; p->next = new; -
Delete after p: tmp = p->next; p->next = tmp->next; free(tmp);
Worked example
Problem. Why must insertHead take struct node **head instead of struct node *head?
Solution. C passes the pointer by value, so assigning to head inside the function changes only a copy. A pointer to the head pointer lets the function update the caller head.
Reversing, finding the middle, and cycle detection
- Iterative reversal uses three pointers: prev = NULL, cur = head; while (cur) { next = cur->next; cur->next = prev; prev = cur; cur = next; } head = prev; — O(n) time, O(1) space.
- Recursive reversal also works in O(n) time but uses O(n) stack space.
- Middle node with slow/fast pointers: both start at head; slow moves 1 step, fast moves 2 steps while (fast && fast->next). When fast reaches the end, slow is at the middle (for an even count it ends at the second middle node).
- k-th node from the end: move a first pointer k nodes ahead, then advance both until the first becomes NULL; the second pointer is at the k-th node from the end. One pass, O(1) space.
- Cycle detection (Floyd tortoise and hare): slow moves 1, fast moves 2; if they ever meet there is a cycle; if fast reaches NULL there is none. O(n) time, O(1) space.
- A list with a cycle never terminates a plain traversal; GATE stems usually say "assume the list has no cycle".
Worked example
Problem. struct node *f(struct node *h) { struct node *p = NULL, *c = h, *n; while (c) { n = c->next; c->next = p; p = c; c = n; } return p; } What does f do to 1→2→3?
Solution. It reverses the list in place and returns the new head 3, giving 3→2→1.
Doubly and circular lists
- A doubly linked list node has prev and next pointers. It supports traversal in both directions and deletion of a node given only a pointer to it in O(1) (unlink using node->prev and node->next).
- The price is one extra pointer per node and more pointer updates on insert/delete (four pointer changes for a middle insert).
- In a linear doubly list with n nodes, exactly 2 pointer fields are NULL (head->prev and tail->next); a singly list has 1 NULL (tail->next).
- Circular list: the last node points back to the first. With only a tail pointer, both insertion at the front (tail->next) and at the rear are O(1); useful for round-robin scheduling.
- Circular traversal stops when the pointer returns to the starting node, not at NULL. A mistaken while(p != NULL) loops forever.
- Singly list: deleting a given node X (not the tail) can be done in O(1) by copying the next node data into X and deleting the next node, but this fails for the last node.
| Feature | Singly | Doubly | Circular singly |
|---|---|---|---|
| Pointers per node | 1 | 2 | 1 |
| Backward traversal | No | Yes | No |
| Delete given node ptr | O(n) (need prev) | O(1) | O(n) |
| NULL pointers (n nodes) | 1 | 2 | 0 |
Worked example
Problem. How many pointer assignments are needed to delete a middle node X in a doubly list?
Solution. Two: X->prev->next = X->next and X->next->prev = X->prev (then free X).
Linked list vs array
- Array: contiguous memory, O(1) random access, fixed size (or amortised resize), inserting or deleting in the middle shifts elements O(n), excellent cache locality.
- Linked list: non-contiguous, O(n) access, grows one node at a time, O(1) insertion/deletion once the position is known, extra memory for pointers, poor cache locality.
- Binary search needs random access, so it works on a sorted array in O(log n) but not on a linked list (O(n) search).
- Merge sort suits linked lists (O(n log n), O(1) extra space for merging), while quick sort and heap sort prefer arrays.
- Stacks and queues are naturally implemented with linked lists when the maximum size is unknown.
- Memory: array of n ints uses n × 4 bytes; a singly list uses n × (4 + pointer size) bytes (plus allocator overhead).
| Operation | Array | Linked list |
|---|---|---|
| Access i-th element | O(1) | O(n) |
| Insert at front | O(n) | O(1) |
| Insert at end | O(1) amortised | O(n) (O(1) with tail) |
| Search unsorted | O(n) | O(n) |
| Search sorted | O(log n) | O(n) |
| Cache locality | Excellent | Poor |
Worked example
Problem. Which structure is better for frequently inserting at the front of a sequence?
Solution. A linked list: insert at head is O(1), while an array must shift all n elements.
GATE exam tricks — linked list code reading
- Draw the list with box-and-arrow notation and number each pointer assignment. Re-draw after EVERY statement; never trust a mental picture.
- The golden ordering rule: connect the NEW node to the rest of the list before you cut the old link. Wrong order = lost tail or a self-loop.
- Spot the loop invariant: in the reversal loop prev is always the head of the already-reversed part, and curr is the head of the unprocessed part.
- Recursion on lists: "print then recurse" prints in list order; "recurse then print" prints in reverse order. Same before/after rule as plain recursion.
- Counting traps: a loop while (p->next != NULL) stops AT the last node; while (p != NULL) walks off the end. Crash on empty list if p->next is used with head == NULL.
- Two-pointer facts: when fast has moved 2n steps slow has moved n; slow is at the middle (second middle for even length). In a cycle of length L the pointers meet within L moves of slow entering the cycle.
- Complexity one-liners: sorted insert O(n), delete after a known node O(1), delete a known node in a doubly list O(1), delete last node in a singly list O(n), merge two sorted lists O(m + n).
- Choosing structure: frequent insert/delete at known positions -> list; frequent indexed access or binary search -> array.
Worked example
Problem. struct node *g(struct node *h) { if (h == NULL || h->next == NULL) return h; struct node *r = g(h->next); h->next->next = h; h->next = NULL; return r; } What does g(1->2->3->NULL) return?
Solution. It reverses recursively. g(3) returns 3. At node 2: 3->next = 2, 2->next = NULL, return 3. At node 1: 2->next = 1, 1->next = NULL, return 3. Result: 3->2->1->NULL, head = 3. Time O(n), stack O(n).
Worked trace: delete the second node and count NULLs
- Delete the node after p: tmp = p->next; p->next = tmp->next; free(tmp). Draw the three pointers before and after.
- Deleting the head must update head itself; deleting the tail of a singly list must also update the tail pointer if one is kept.
- A doubly list of n >= 1 nodes always has exactly 2 NULL pointers; a circular singly list has none.
Worked example
Problem. A singly list holds 5 -> 8 -> 12 -> 20 -> NULL. Pointer p points at 8. After tmp = p->next; p->next = tmp->next; free(tmp); what are the list and its length?
Solution. tmp points at 12. p->next now points at 20, so 12 is unlinked and freed. List: 5 -> 8 -> 20 -> NULL, length 3.
Exam tips
- Draw boxes and arrows; update pointers in the order that never loses the rest of the list.
- Check the empty-list, single-node, head, and tail cases for every code fragment.
- Remember that a singly list cannot delete a given node in O(1) without the predecessor (except the copy trick).
- Use slow/fast pointers for the middle and for cycle detection; know that for even length slow lands on the second middle.
- Recursive list functions use O(n) stack space even when they allocate nothing.
10 GATE-style MCQs for Linked Lists with full explanations. Attempt each question before revealing the answer.
The time complexity of inserting a new node at the head of a singly linked list with n nodes is:
Show answer & explanation
Answer: C
Two pointer assignments (new->next = head; head = new) take constant time.
With only a head pointer, the time to delete the last node of a singly linked list of n nodes is:
Show answer & explanation
Answer: B
You must traverse to the second-last node to set its next to NULL, which takes O(n).
struct node *f(struct node *h) { struct node *p = NULL, *c = h, *n; while (c) { n = c->next; c->next = p; p = c; c = n; } return p; } For input 1→2→3, f returns a pointer to the list:
Show answer & explanation
Answer: B
The loop reverses every next pointer in place; p ends at the old last node, so the returned list is 3→2→1.
In a 6-node list (nodes numbered 1 to 6), slow = fast = head initially; loop: while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }. Which node is slow pointing to at the end?
Show answer & explanation
Answer: B
Iterations: (slow, fast) = (1,1) → (2,3) → (3,5) → (4,NULL). The loop stops with slow at node 4, the second middle node.
In a doubly linked list, given a pointer to a node X (not the head or tail), the time to delete X is:
Show answer & explanation
Answer: A
X->prev and X->next let you relink neighbours directly with two assignments.
The best possible time to search for a key in a sorted singly linked list of n nodes (no extra structure) is:
Show answer & explanation
Answer: C
Without random access binary search is not possible, so in the worst case every node is examined.
A circular singly linked list is accessed only through a pointer to its last (tail) node. Which operations can be done in O(1)?
Show answer & explanation
Answer: C
The head is tail->next. Inserting after tail (and not moving tail) adds at the front; moving tail to the new node adds at the rear. Both are O(1).
In a linear (non-circular) doubly linked list with n ≥ 1 nodes, how many pointer fields (prev and next together) are NULL?
Show answer & explanation
Answer: C
head->prev and tail->next are NULL; every other pointer points to a node.
To insert node n after node p in a singly linked list, the correct sequence is:
Show answer & explanation
Answer: B
Save the old successor in n->next first, then link p to n. Option A makes n->next point to n itself.
Which technique detects a cycle in a linked list in O(n) time using O(1) extra space?
Show answer & explanation
Answer: B
Slow moves one step and fast two; they meet inside a cycle, otherwise fast reaches NULL. Hashing works but needs O(n) extra space.
Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.
int len(struct node *h) { return h ? 1 + len(h->next) : 0; } What is the auxiliary (stack) space used for a list of n nodes?
Show answer & explanation
Answer: C) O(n)
The recursion goes n + 1 calls deep, so the stack uses O(n) space.
With both head and tail pointers, inserting at the tail of a singly linked list takes:
Show answer & explanation
Answer: A) O(1)
tail->next = new; tail = new; takes constant time.
After head = head->next; in C code that deletes the first node, which extra step avoids a memory leak?
Show answer & explanation
Answer: B) Save the old head and free() it
The old first node still occupies heap memory; keep a temporary pointer to it and call free on it.
void f(struct node *h) { if (h == NULL) return; f(h->next); printf("%d ", h->data); } What is printed for 1→2→3?
Show answer & explanation
Answer: B) 3 2 1
The print follows the recursive call, so nodes are printed while unwinding, last node first.
Inserting a key into a sorted singly linked list of n nodes (keeping order) takes, in the worst case:
Show answer & explanation
Answer: C) O(n)
The correct position may be at the end, so up to n nodes are examined.
Accessing the i-th element is O(1) in which structure?
Show answer & explanation
Answer: C) Array
Arrays compute the address directly from the index; lists need traversal.
How many pointer fields does each node of a doubly linked list contain?
Show answer & explanation
Answer: B) 2
One next pointer and one prev pointer.
Merging two sorted singly linked lists of lengths m and n by relinking nodes takes time:
Show answer & explanation
Answer: B) O(m + n)
Each node is examined once while repeatedly picking the smaller head.
In a 7-node singly list, a first pointer is advanced 2 nodes from the head, then first and second (starting at the head) move together until first is NULL. Second then points to which node (counted from the head)?
Show answer & explanation
Answer: B) 6th
First starts at node 3 and needs 5 moves to reach NULL; second moves from node 1 to node 6, i.e. the 2nd node from the end.
Which operation is NOT O(1) in a singly linked list that has only a head pointer?
Show answer & explanation
Answer: C) Insert at tail
Reaching the tail requires traversing all n nodes; the other operations need only a few pointer updates.
Topic FAQs
Why is inserting at the tail of a singly linked list O(n)?
With only a head pointer you must walk the entire list to reach the last node; keeping a tail pointer makes it O(1).
Why can binary search not be used efficiently on a linked list?
Reaching the middle node takes O(n) pointer hops, so each step is costly and the total stays O(n).
How many extra pointers does a doubly list need compared with a singly list?
One extra pointer (prev) per node.
Does reversing a linked list need extra memory?
The iterative version uses only three pointers, so O(1) extra space; the recursive version uses O(n) stack space.
Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.