Skip to content
Visual explainer 5h to learn 4 steps

Linked lists

Reverse, merge and detect cycles without bugs.

By Invicly Tech, , in Interview Preparation. About 10 minutes to read.

Topic 6 of 27

In short

A linked list is a chain of nodes where each points to the next. Problems test pointer rewiring without losing nodes, often using a dummy head or fast and slow pointers.

Explained simply

A linked list is a chain of small boxes called nodes. Each node holds a value and an arrow pointing to the next node. Unlike an array, the nodes can live anywhere in memory. To reach the tenth node you must follow nine arrows from the start, which is called the head.

Think of a treasure hunt where each clue tells you where the next clue is hidden. Adding a new clue in the middle is easy: change one arrow. But finding clue number 50 means walking through 49 clues first. That is the trade-off: cheap inserts, slow lookups.

Linked list questions are really about careful arrow surgery. If you change node.next before saving where it pointed, the rest of the list is lost for good. So the golden habit is: save the next node in a variable first, then rewire.

Draw it. Sketch three or four boxes with arrows and update them step by step as your code runs. Almost every linked list bug, like a null pointer or a lost node, shows up on paper in under a minute.

Press Play on a diagram to walk through it one step at a time.

FlowReverse a list in place
  1. 1
    Start: prev = None

    cur = head; nothing reversed yet

  2. 2
    Save next

    nxt = cur.next so the rest is not lost

  3. 3
    Flip the pointer

    cur.next = prev

  4. 4
    Advance both

    prev = cur, cur = nxt

  5. 5
    Return prev

    prev is the new head when cur is None

CompareTwo helper techniques
Dummy head
  • Fake node before the real head
  • No special case for the first node
  • Return dummy.next
  • Merge lists, remove nodes
Fast and slow pointers
  • Fast moves 2, slow moves 1
  • They meet if there is a cycle
  • Slow ends at the middle
  • Cycle detection, find middle
FlowReorder List: 1, 2, 3, 4, 5
  1. Step 1
    Find middle

    slow stops at 3

  2. Step 2
    Split

    1, 2, 3 and 4, 5

  3. Step 3
    Reverse second half

    5, 4

  4. Step 4
    Merge alternately

    1, 5, 2, 4, 3

CompareArray vs linked list
Array
  • Access by index: O(1)
  • Insert in the middle: O(n), items shift
  • Cache friendly: items side by side
  • No extra memory per item
Linked list
  • Access by index: O(n), walk the chain
  • Insert after a known node: O(1)
  • Nodes scattered in memory
  • Extra memory for each next pointer

In depth

Finding where a cycle starts

Floyd's algorithm moves slow one step and fast two steps. If they meet, there is a cycle. To find the node where the cycle begins, reset one pointer to the head and move both one step at a time. They meet again exactly at the cycle start.

Why? Say the start is a steps from the head, they met b steps into the cycle, and the cycle has length c. Fast walked twice as far as slow, which works out to a = kc - b for some whole number k. So walking a more steps from the meeting point lands on the start, just like walking a steps from the head. O(n) time, O(1) space.

The gap trick for "nth from the end"

You cannot walk backwards in a singly linked list, and counting the length first takes two passes. Instead, move a fast pointer n steps ahead, then move fast and slow together. When fast reaches the last node, slow sits right before the node to delete.

Start both at a dummy node that points to the head. Then deleting the head itself needs no special case, and you return dummy.next at the end.

  • Dummy points to head
  • Advance fast n steps
  • Move both until fast.next is null
  • slow.next = slow.next.next
FlowRemove 2nd from end of 1, 2, 3, 4, 5
  1. 1
    Start at dummy

    dummy points to 1

  2. 2
    Advance fast 2

    fast on node 2

  3. 3
    Move both

    Until fast.next is null: fast 5, slow 3

  4. 4
    Unlink

    slow.next = slow.next.next drops 4

  5. 5
    Return dummy.next

    1, 2, 3, 5

Combining small tools: Reorder List

Many hard-looking list problems are three easy ones glued together. Reorder List turns 1, 2, 3, 4, 5 into 1, 5, 2, 4, 3. Step one: find the middle with fast and slow pointers. Step two: reverse the second half. Step three: merge the two halves by alternating nodes.

Palindrome Linked List uses the same first two steps, then compares the halves. If you can write middle, reverse and merge from memory, you can assemble a dozen problems in O(n) time and O(1) space.

LRU cache: a list plus a map

An LRU (least recently used) cache evicts the item that was used longest ago. A hash map gives O(1) lookup by key. A doubly linked list, where nodes point both forwards and backwards, keeps items in usage order and can unlink any node in O(1) once you hold a reference to it.

On get, move the node to the front. On put, insert at the front, and if the cache is too big, remove the node at the back and delete its key from the map. Dummy head and tail nodes remove all null checks. Java's LinkedHashMap can do this for you, but interviewers usually want it by hand.

MapLRU cache parts and moves
LRU cache
  • Hash map
    • key to node
    • O(1) lookup
  • Doubly linked list
    • Most recent at the front
    • Least recent at the back
    • O(1) unlink
  • get(key)
    • Move node to the front
  • put(key, value)
    • Insert at the front
    • Too big: drop back node and its key

Learn it in 4 short steps

About 1h 15m each. Track them with a timer in your plan.

  1. 1
    Implement a singly linked list~1h 15m
  2. 2
    Use dummy heads and fast/slow pointers~1h 15m
  3. 3
    Practice: Reverse Linked List, Merge Two Lists~1h 15m
  4. 4
    Practice: Linked List Cycle, Remove Nth Node~1h 15m

Key points

  • Reversal is O(n) time and O(1) space when done in place.
  • Fast and slow pointers detect a cycle in O(n) time and O(1) space.
  • To remove the Nth node from the end, move one pointer n steps ahead first.
  • Draw the boxes and arrows before coding; most bugs are lost references.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def reverse(head):
    prev, cur = None, head
    while cur:
        nxt = cur.next
        cur.next = prev
        prev, cur = cur, nxt
    return prev

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

Remove the 2nd node from the end of 1, 2, 3, 4, 5

dummy, 1, 2, 3, 4, 5. Move fast 2 steps from dummy: fast is at 2. Move both until fast.next is null: (slow 1, fast 3), (slow 2, fast 4), (slow 3, fast 5). Now slow is at 3 and slow.next is 4, the 2nd node from the end. Set 3.next = 5. Result 1, 2, 3, 5. One pass, O(1) extra space.

java
ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode dummy = new ListNode(0, head), fast = dummy, slow = dummy;
    for (int i = 0; i < n; i++) fast = fast.next;
    while (fast.next != null) {
        fast = fast.next;
        slow = slow.next;
    }
    slow.next = slow.next.next;
    return dummy.next;
}

Finding the start of a cycle

List 1, 2, 3, 4, 5, and 5 points back to 3. Both pointers start at 1. Step 1: slow 2, fast 3. Step 2: slow 3, fast 5. Step 3: slow 4, fast 4, so they meet. Reset slow to the head (1) and keep fast at 4. Move both one step: slow 2, fast 5. Again: slow 3, fast 3. They meet at 3, the cycle start.

java
ListNode detectCycle(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) {
            slow = head;
            while (slow != fast) { slow = slow.next; fast = fast.next; }
            return slow;
        }
    }
    return null;
}

Quick reference

  • Save next before rewiring: ListNode nxt = cur.next;
  • Dummy node before head removes head special cases; return dummy.next
  • Middle: slow 1 step, fast 2; loop while fast != null && fast.next != null
  • Cycle start: after meeting, reset one pointer to head and move both 1 step
  • Nth from end: give fast an n-step head start
  • Recursive list code uses O(n) stack; iterative uses O(1)
  • LRU cache = HashMap + doubly linked list

Common mistakes

  • Overwriting cur.next before saving it, losing the rest of the list.
  • Not checking fast.next before fast.next.next.
  • Forgetting the empty-list and single-node cases.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1After fast and slow pointers meet inside a cycle, how do you find the cycle start?

Question 2

2Why use a dummy node when removing the nth node from the end?

Question 3

3What is the space cost of reversing a list recursively?

Question 4

4Which pair of structures gives O(1) get and put for an LRU cache?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Merge Two Sorted Lists into one sorted list by splicing the existing nodes together.

  2. Exercise 2medium

    Palindrome Linked List: decide whether the values read the same both ways, in O(n) time and O(1) extra space.

  3. Exercise 3hard

    Design an LRU cache with get(key) and put(key, value), both in O(1).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Are linked lists used in real Java code?
Rarely directly. ArrayList is faster for almost everything because of memory locality, but linked structures sit inside LinkedHashMap, LRU caches and many queues, and they are a favourite way to test pointer reasoning.
Do I need to write the ListNode class in an interview?
Usually the platform provides it. If not, write a short class with int val, ListNode next and a constructor before you start.
Should I write list solutions iteratively or recursively?
Iterative is safer for long lists because recursion uses O(n) stack and can overflow. Recursion is fine if it is clearer, but mention the stack cost.

Go deeper

ShareXLinkedInWhatsApp