Data Structures & Algorithms chapters (13)
  1. 01Introduction to DSA
  2. 02Arrays & Strings Algorithms
  3. 03Searching & Sorting Algorithms
  4. 04Asymptotic Analysis & Complexity
  5. 05Linked Lists
  6. 06Stacks & Queues
  7. 07Hashing & Hash Tables
  8. 08Recursion & Backtracking
  9. 09Binary Trees & BST
  10. 10Heaps & Priority Queues
  11. 11Graphs & Graph Algorithms
  12. 12Greedy Algorithms & Bit Manipulation
  13. 13Dynamic Programming (DP)

Chapter 05

Linked Lists

4 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

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.

1

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.

Singly linked list: head → nodes with data+next → null
Singly linked list: head → nodes with data+next → null

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 tail O(n), delete head O(1), delete tail O(n), search O(n).
  • Memory leak risk in C/C++: free nodes on delete; garbage collected in Java/Python.

Example

Code
Common 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.next
2

Doubly 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.

Doubly linked list with prev and next pointers
Doubly linked list with prev and next pointers

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

Delete a given node: node.

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

  • prev / next: Backward and forward pointers.
  • Circular list: Last node links back to first; no null terminator.
  • Insert after node p: n.prev=p; n.next=p.next; if p.next: p.next.prev=n; p.next=n (order matters).

Example

Code
LRU 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]
3

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.

Reversing a linked list with prev, current, next pointers
Reversing a linked list with prev, current, next pointers

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 = head and head.

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

Code
Reversal 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 ok
4

Floyd'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.

Floyd cycle detection: slow and fast pointers meet in a loop
Floyd cycle detection: slow and fast pointers meet in a loop

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

  • Tortoise / hare: Slow (1 step) and fast (2 steps) pointers.
  • Cycle entry: First node that belongs to the cycle.

Example

Code
Cycle 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 slow

Solved examples

Example 01 · Basic

Trace reverse_iter on 1 -> 2 -> 3.

Given Data:
    Required To Find:

    Final list

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: prev=None, cur=1: nxt=2, 1.next=None, prev=1, cur=2.
    Step 2: cur=2: nxt=3, 2.next=1, prev=2, cur=3.
    Step 3: cur=3: nxt=None, 3.next=2, prev=3, cur=None.
    Final Answer: 3 -> 2 -> 1 (head is old tail)

    Approach note: Always save next before overwriting it.

    Example 02 · Intermediate

    List of 10 nodes, cycle of length 4 starting at node 7 (1-indexed). Where do slow and fast meet and what happens next?

    Given Data:
      Required To Find:

      Meeting and entry

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: L = 6 nodes before entry, C = 4.
      Step 2: When slow enters (after 6 steps) fast is 6 steps ahead inside the cycle: 6 mod 4 = 2 positions past the entry.
      Step 3: Gap to close = C - 2 = 2 more steps (gap shrinks by 1 per step), so they meet 2 nodes after the entry.
      Step 4: Reset one pointer to head; moving both 1 step each, they meet at node 7.
      Final Answer: Meeting inside cycle (2 nodes past entry); phase 2 finds node 7

      Approach note: Meeting point is x from entry, and L = kC - x.

      Example 03 · Advanced

      Delete a node given only a pointer to it (not tail) in a singly list. Complexity and limitation?

      Given Data:
        Required To Find:

        Method

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Copy next.val into node.val.
        Step 2: Set node.next = node.next.next.
        Step 3: O(1) time, but it fails for the tail and changes node identity (breaks external references to the next node).
        Final Answer: O(1) via value copy; invalid for tail node

        Approach note: Doubly lists do not need this trick.

        Example 04 · Intermediate

        Find the middle node of a singly linked list 1→2→3→4→5 using slow/fast pointers.

        Given Data:
          Required To Find:

          Middle value

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: slow moves 1, fast moves 2
          Step 2: When fast hits end, slow is at middle
          Step 3: Middle is 3
          Final Answer: 3

          Approach note: For even length, state whether you want the first or second middle.

          Real-world applications

          DSA

          Using Linked Lists in real projects

          LRU cache (hash map + doubly list), undo history, adjacency lists, memory allocators, polynomial arithmetic.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          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

          1. Singly: insert head O(1), tail O(n) (O(1) with tail ptr), delete tail O(n)
          2. Doubly: O(1) delete given node; powers LRU (hashmap + doubly list)
          3. Reverse: nxt=cur.next; cur.next=prev; move prev/cur; O(n) O(1)
          4. Floyd: speeds 1,2; meet in cycle; reset to head to find entry; L = kC - x
          5. Use dummy node, compare identity, check None before .next

          Practice questions

          Question 1 · MCQ (GATE)

          Deleting the last node of a singly list with only head pointer takes:

          Question 2 · MCQ (Interview)

          Space used by iterative reversal:

          Question 3 · MCQ (Interview)

          In Floyd cycle detection, fast moves:

          Question 4 · MCQ (GATE)

          Which structure gives O(1) delete of a given node?

          Question 5 · MCQ (Interview)

          To get the middle of a singly list in one pass use: