Chapter 05
Linked Lists
4 topics · 1 sections · beginner-friendly study notes · Updated
A linked list stores nodes connected by pointers; it gives O(1) insertion/deletion given a node reference but O(n) access.
Pointer manipulation (reversal, fast-slow pointers, dummy nodes) is the core skill.
Linked-list pointer manipulation is a staple interview filter and GATE tests complexities of operations with head/tail pointers.
LRU cache (hash map + doubly list), undo history, adjacency lists, memory allocators, polynomial arithmetic.
Singly Linked List
A singly linked list is a sequence of nodes, each holding data and a pointer to the next node; the list is accessed through head. The last node points to null/None.
In short: A chain where each box only knows the next box.

Think about it
Foundation for stacks, queues, hash chaining and graph adjacency lists; operation costs are asked verbatim in GATE.
Access k-th element: O(k).
Search: O(n).
Insert at head: O(1).
Insert at tail: O(n) with only head pointer, O(1) with tail pointer.
Delete head: O(1).
Delete a given node needs its predecessor: O(n) to find it (the trick of copying next node data and unlinking works for non-tail nodes in O(1)).
Delete tail in singly list is O(n) even with tail pointer (need predecessor).
Extra memory: one pointer per node (8 bytes on 64-bit).
No random access and poor cache locality compared to arrays.
Dummy (sentinel) head removes special-casing of head deletion/insertion.
Middle element: slow moves 1, fast moves 2; when fast hits the end slow is at the middle.
k-th from end: advance fast k steps then move both.
Merge two sorted lists in O(m+n), O(1) space.
Always check null before dereferencing next and handle empty list, single node, and deleting the head.
Key points
- Head: Pointer to the first node.
- Sentinel / dummy node: Fake node before head to unify edge cases.
- Node: Record with data and next pointer.
- Costs (head only): insert head
O(1), insert tailO(n), delete headO(1), delete tailO(n), searchO(n). - Memory leak risk in C/C++: free nodes on delete; garbage collected in Java/Python.
Read more
Example
CodeCommon singly-list routines:
class Node:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
def delete_value(head, x):
dummy = Node(0, head)
cur = dummy
while cur.next:
if cur.next.val == x:
cur.next = cur.next.next
break
cur = cur.next
return dummy.next
def middle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow
def kth_from_end(head, k):
fast = slow = head
for _ in range(k): fast = fast.next
while fast:
slow, fast = slow.next, fast.next
return slow
def merge_sorted(a, b):
dummy = tail = Node(0)
while a and b:
if a.val <= b.val: tail.next, a = a, a.next
else: tail.next, b = b, b.next
tail = tail.next
tail.next = a or b
return dummy.nextDoubly Linked List
A doubly linked list node stores data, prev and next pointers, enabling traversal in both directions and O(1) deletion of a node when you hold a reference to it.
In short: Each box knows both its neighbours, so you can walk backward and unlink yourself directly.

Think about it
O(1) arbitrary deletion is the reason doubly lists power LRU caches and deques.
Insert/delete at head and tail are O(1) when both head and tail pointers are maintained (a deque).
prev.
next = node.
next; node.
next.
prev = node.
prev: O(1), no search for the predecessor.
Cost: two pointers per node (16 bytes on 64-bit) and more pointer updates (4 per insertion in the middle).
Circular doubly list with a sentinel node removes all null checks (Linux kernel list_head, Java LinkedList is doubly).
LRU cache: HashMap key->node plus doubly list ordered by recency gives O(1) get and put: move accessed node to the front, evict the tail.
XOR linked list stores prev XOR next in one pointer to save space (not available in managed languages).
Common bug: forgetting to update prev of the node after the inserted one, or updating pointers in the wrong order and losing the rest of the list.
Key points
Example
CodeLRU cache with doubly list:
class DNode:
def __init__(self, key=0, val=0):
self.key, self.val = key, val
self.prev = self.next = None
class LRU:
def __init__(self, cap):
self.cap, self.map = cap, {}
self.head, self.tail = DNode(), DNode() # sentinels
self.head.next, self.tail.prev = self.tail, self.head
def _remove(self, n):
n.prev.next, n.next.prev = n.next, n.prev
def _add_front(self, n):
n.next, n.prev = self.head.next, self.head
self.head.next.prev = n; self.head.next = n
def get(self, k):
if k not in self.map: return -1
n = self.map[k]; self._remove(n); self._add_front(n)
return n.val
def put(self, k, v):
if k in self.map: self._remove(self.map[k])
n = self.map[k] = DNode(k, v); self._add_front(n)
if len(self.map) > self.cap:
lru = self.tail.prev; self._remove(lru); del self.map[lru.key]Reversing a Linked List
Reversing flips every next pointer so the old tail becomes the head. Iterative reversal uses three pointers (prev, cur, nxt) in O(n) time and O(1) space; recursive reversal uses O(n) call-stack space.
In short: Walk down the list and make each node point backward instead of forward.

Think about it
Most frequently asked pointer-manipulation question; its variants test pointer discipline.
Iterative: save nxt = cur.
next, set cur.
next = prev, advance prev = cur, cur = nxt.
At the end prev is the new head.
Recursive: reverse the rest, then make head.
next.
next = None.
Reversing a sub-list [m, n]: walk to node m-1, then perform n-m head insertions.
Reverse in groups of k: reverse each group, connect the tail of the previous group to the new group head; if fewer than k nodes remain, leave them as is; O(n) time, O(1) space.
Palindrome check in O(1) space: find middle with slow/fast, reverse the second half, compare, restore.
Reverse of a doubly list: swap prev and next for every node and set head to the old tail.
Edge cases: empty list, one node, losing the reference to the rest of the list by overwriting next before saving it.
Key points
- In-place reversal: Reuse existing nodes;
O(1)extra space. - Group reversal: Reverse every k nodes, keep remainder.
Example
CodeReversal and palindrome check:
def reverse_iter(head):
prev, cur = None, head
while cur:
nxt = cur.next
cur.next = prev
prev, cur = cur, nxt
return prev
def reverse_rec(head):
if not head or not head.next:
return head
new_head = reverse_rec(head.next)
head.next.next = head
head.next = None
return new_head
def is_palindrome(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
second = reverse_iter(slow)
a, b, ok = head, second, True
while b:
if a.val != b.val: ok = False; break
a, b = a.next, b.next
reverse_iter(second) # restore (optional)
return okFloyd's Cycle Detection
Floyd's tortoise-and-hare algorithm uses two pointers moving at speeds 1 and 2; if the list has a cycle they must meet inside it. Time O(n), space O(1). A second phase finds the node where the cycle begins.
In short: A fast runner and a slow runner on a looping track will eventually meet.

Think about it
Classic O(1)-space trick; the entry-point proof is a common interview follow-up.
Detection: if fast or fast.
next becomes None there is no cycle.
Why they meet: once both are in the cycle, the gap changes by 1 each step, so it hits 0 (the cycle length is finite).
Cycle start: after meeting, reset one pointer to head and move both one step at a time; they meet at the cycle entry.
Proof: let L = distance head to entry, C = cycle length, x = distance entry to meeting point.
Slow travelled L + x, fast 2(L + x) = L + x + kC, so L = kC - x, meaning that walking L steps from the meeting point lands on the entry (after k-1 full loops).
Cycle length: from the meeting point count steps until return.
Alternative: hash set of visited nodes is O(n) space.
Same idea finds duplicate number in an array treated as a functional graph (a[i] points to a[a[i]]) in O(n) time O(1) space.
Fast pointer with step 3 also works but needs more careful gcd reasoning; step 2 is standard.
Key points
Read more
Example
CodeCycle detection and entry:
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False
def cycle_start(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
slow = head
while slow is not fast:
slow, fast = slow.next, fast.next
return slow
return None
def find_duplicate(nums): # values in 1..n, n+1 numbers
slow = fast = nums[0]
while True:
slow, fast = nums[slow], nums[nums[fast]]
if slow == fast: break
slow = nums[0]
while slow != fast:
slow, fast = nums[slow], nums[fast]
return slowSolved examples
Trace reverse_iter on 1 -> 2 -> 3.
Final list
Formula Applied:—Approach note: Always save next before overwriting it.
List of 10 nodes, cycle of length 4 starting at node 7 (1-indexed). Where do slow and fast meet and what happens next?
Meeting and entry
Formula Applied:—Approach note: Meeting point is x from entry, and L = kC - x.
Delete a node given only a pointer to it (not tail) in a singly list. Complexity and limitation?
Method
Formula Applied:—Approach note: Doubly lists do not need this trick.
Find the middle node of a singly linked list 1→2→3→4→5 using slow/fast pointers.
Middle value
Formula Applied:—Approach note: For even length, state whether you want the first or second middle.
Real-world applications
Using Linked Lists in real projects
LRU cache (hash map + doubly list), undo history, adjacency lists, memory allocators, polynomial arithmetic.
Common mistakes
❌ Myth: Linked list insertion is always O(1).
Why this is wrong: You must first reach the position, which is O(n) unless you already hold a node reference.
✅ Verified Truth: Insert/delete after a known node is O(1); search + insert is O(n).
⚠️ Exam Tip: GATE: specify "given pointer to node" vs "given index".
❌ Myth: Linked lists are faster than arrays for everything except indexing.
Why this is wrong: Pointer chasing causes cache misses; arrays often win even for middle inserts at moderate n.
✅ Verified Truth: Choose lists when you need stable references or O(1) splicing, arrays otherwise.
⚠️ Exam Tip: Mention cache locality in interviews.
❌ Myth: Floyd's algorithm needs the fast pointer to move exactly 2 and compare values.
Why this is wrong: Compare node identity (is), not values, because duplicates are normal.
✅ Verified Truth: Compare references.
⚠️ Exam Tip: Using == on values gives false cycles.
Revision notes
A linked list stores nodes connected by pointers; it gives O(1) insertion/deletion given a node reference but O(n) access. Pointer manipulation (reversal, fast-slow pointers, dummy nodes) is the core skill.
High-Yield Quick Revision Points
- Singly: insert head O(1), tail O(n) (O(1) with tail ptr), delete tail O(n)
- Doubly: O(1) delete given node; powers LRU (hashmap + doubly list)
- Reverse: nxt=cur.next; cur.next=prev; move prev/cur; O(n) O(1)
- Floyd: speeds 1,2; meet in cycle; reset to head to find entry; L = kC - x
- Use dummy node, compare identity, check None before .next
Practice questions
Deleting the last node of a singly list with only head pointer takes:
Space used by iterative reversal:
In Floyd cycle detection, fast moves:
Which structure gives O(1) delete of a given node?
To get the middle of a singly list in one pass use: