Skip to main content

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.

~4 hrs ~1–1.5 marks · High 10 samples · 10 practice · 10 cards

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 headO(1)
Insert at tailO(n)
Delete headO(1)
Delete last nodeO(n)
Search / access k-thO(n) / O(k)
Insert or delete after a given node pointerO(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).

Singly linked list head to nodes A, B, C each with data and next fields, ending in NULL
Each node = data + next; the last next is NULL. Lose head and the list is gone.

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.

Inserting node X between P and Q with step 1 x->next = q and step 2 p->next = x
Link the new node forward first (x->next = p->next), then redirect p->next.

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.

Reversal of 1 to 2 to 3 using prev, curr and next pointers, with the loop body shown
Save next, flip curr->next to prev, then advance prev and curr.

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.
FeatureSinglyDoublyCircular singly
Pointers per node121
Backward traversalNoYesNo
Delete given node ptrO(n) (need prev)O(1)O(n)
NULL pointers (n nodes)120

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).
OperationArrayLinked list
Access i-th elementO(1)O(n)
Insert at frontO(n)O(1)
Insert at endO(1) amortisedO(n) (O(1) with tail)
Search unsortedO(n)O(n)
Search sortedO(log n)O(n)
Cache localityExcellentPoor

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.
Exam pattern · 10 questions

GATE sample questions & answers

10 GATE-style MCQs for Linked Lists with full explanations. Attempt each question before revealing the answer.

Q1 Singly list insertion

The time complexity of inserting a new node at the head of a singly linked list with n nodes is:

  • A) O(n)
  • B) O(log n)
  • C) O(1)
  • D) O(n log n)
Show answer & explanation

Answer: C

Two pointer assignments (new->next = head; head = new) take constant time.

Q2 Singly list deletion

With only a head pointer, the time to delete the last node of a singly linked list of n nodes is:

  • A) O(1)
  • B) O(n)
  • C) O(log n)
  • D) O(n²)
Show answer & explanation

Answer: B

You must traverse to the second-last node to set its next to NULL, which takes O(n).

Q3 List reversal

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:

  • A) 1→2→3
  • B) 3→2→1
  • C) 3 only
  • D) 1 only
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.

Q4 Slow and fast pointers

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?

  • A) Node 3
  • B) Node 4
  • C) Node 5
  • D) Node 6
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.

Q5 Doubly list

In a doubly linked list, given a pointer to a node X (not the head or tail), the time to delete X is:

  • A) O(1)
  • B) O(n)
  • C) O(log n)
  • D) O(n²)
Show answer & explanation

Answer: A

X->prev and X->next let you relink neighbours directly with two assignments.

Q6 Search

The best possible time to search for a key in a sorted singly linked list of n nodes (no extra structure) is:

  • A) O(1)
  • B) O(log n)
  • C) O(n)
  • D) O(sqrt n)
Show answer & explanation

Answer: C

Without random access binary search is not possible, so in the worst case every node is examined.

Q7 Circular list

A circular singly linked list is accessed only through a pointer to its last (tail) node. Which operations can be done in O(1)?

  • A) Insert at the front only
  • B) Insert at the rear only
  • C) Both insert at the front and at the rear
  • D) Neither
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).

Q8 Doubly list structure

In a linear (non-circular) doubly linked list with n ≥ 1 nodes, how many pointer fields (prev and next together) are NULL?

  • A) 0
  • B) 1
  • C) 2
  • D) n
Show answer & explanation

Answer: C

head->prev and tail->next are NULL; every other pointer points to a node.

Q9 Pointer order

To insert node n after node p in a singly linked list, the correct sequence is:

  • A) p->next = n; n->next = p->next;
  • B) n->next = p->next; p->next = n;
  • C) p->next = n->next; n->next = p;
  • D) n->next = p; p->next = n;
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.

Q10 Cycle detection

Which technique detects a cycle in a linked list in O(n) time using O(1) extra space?

  • A) Hash all node addresses
  • B) Floyd tortoise and hare (slow and fast pointers)
  • C) Reverse the list twice
  • D) Binary search on the list
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.

Topic drill · 10 questions

10 practice questions — Linked Lists

Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.

P1

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?

  • A) O(1)
  • B) O(log n)
  • C) O(n)
  • D) O(n²)
Show answer & explanation

Answer: C) O(n)

The recursion goes n + 1 calls deep, so the stack uses O(n) space.

P2

With both head and tail pointers, inserting at the tail of a singly linked list takes:

  • A) O(1)
  • B) O(n)
  • C) O(log n)
  • D) O(n²)
Show answer & explanation

Answer: A) O(1)

tail->next = new; tail = new; takes constant time.

P3

After head = head->next; in C code that deletes the first node, which extra step avoids a memory leak?

  • A) Nothing is needed
  • B) Save the old head and free() it
  • C) Set head = NULL
  • D) Reverse the list
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.

P4

void f(struct node *h) { if (h == NULL) return; f(h->next); printf("%d ", h->data); } What is printed for 1→2→3?

  • A) 1 2 3
  • B) 3 2 1
  • C) 1 3
  • D) 3
Show answer & explanation

Answer: B) 3 2 1

The print follows the recursive call, so nodes are printed while unwinding, last node first.

P5

Inserting a key into a sorted singly linked list of n nodes (keeping order) takes, in the worst case:

  • A) O(1)
  • B) O(log n)
  • C) O(n)
  • D) O(n log n)
Show answer & explanation

Answer: C) O(n)

The correct position may be at the end, so up to n nodes are examined.

P6

Accessing the i-th element is O(1) in which structure?

  • A) Singly linked list
  • B) Doubly linked list
  • C) Array
  • D) Circular linked list
Show answer & explanation

Answer: C) Array

Arrays compute the address directly from the index; lists need traversal.

P7

How many pointer fields does each node of a doubly linked list contain?

  • A) 1
  • B) 2
  • C) 3
  • D) 0
Show answer & explanation

Answer: B) 2

One next pointer and one prev pointer.

P8

Merging two sorted singly linked lists of lengths m and n by relinking nodes takes time:

  • A) O(m n)
  • B) O(m + n)
  • C) O(log(m + n))
  • D) O(min(m, n))
Show answer & explanation

Answer: B) O(m + n)

Each node is examined once while repeatedly picking the smaller head.

P9

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)?

  • A) 5th
  • B) 6th
  • C) 7th
  • D) 3rd
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.

P10

Which operation is NOT O(1) in a singly linked list that has only a head pointer?

  • A) Insert at head
  • B) Delete head
  • C) Insert at tail
  • D) Insert after a given node
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.

Quick revision · 10 cards

10 flashcards — Linked Lists

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 What is the time complexity of inserting at the head of a singly linked list and why?
Q2 Why is deleting the last node of a singly linked list O(n) when only the head is known?
Q3 How do you reverse a singly linked list iteratively and what are its costs?
Q4 How do slow and fast pointers find the middle of a linked list?
Q5 How does Floyd cycle detection decide that a linked list contains a cycle?
Q6 What are the advantages of a doubly linked list over a singly linked list?
Q7 Why does a function that inserts at the head of a list need a pointer to the head pointer in C?
Q8 How do arrays and linked lists differ in access time and insertion cost?
Q9 Why can binary search not be applied efficiently to a sorted linked list?
Q10 What is the space complexity of the recursive length function for a linked list of n nodes?