cswork / templatesOpen the Line 500 list

STOP 09 · LISTS & TREES

Linked Lists and Pointers

Reverse in place, fast and slow pointers O(n) time · O(1) space

Contest ratings Rating 1232–Rating 1782· median Rating 1507(2 of 27 problems rated by zerotrac)

Open the Line 500 list · stop 09 · 27 problems
Learn first
Leads to
How often asked
asked by 7 companies · in 11 reportsLinkedIn 3, Microsoft 3, Amazon 1, Arista 1, HubSpot 1

Warm up with this one

LC 203Remove Linked List ElementsEasy
Stuck? Peek at the approach

Use a dummy node to unify head and interior deletions while maintaining the predecessor pointer.

Key points

  1. Save next before rewiring. Reversal is three moves: save next, point back, step forward.
  2. When the head may be removed or replaced, start from a dummy node that points at head and return dummy.next.
  3. A fast pointer taking two steps per slow step finds the middle and detects a cycle; for the k-th node from the end, move a lead pointer k steps first, then advance both at the same speed.

Common pitfalls

  • Rewiring head.next before saving it loses the rest of the list.
  • Check that fast and fast.next are non-null before touching fast.next.next.
  • After splitting a list, forgetting to null out the first half's tail creates a cycle when you merge or traverse.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Linked list · insert, delete and reverse by rewiring

List 1 → 2 → 3 → 4: insert 9 at position 2, delete position 0, then reverse

Try your own input
1head234
CurrentDiscovered / computedAnswer
From head
1 → 2 → 3 → 4

Each node holds a value and a pointer to the next node. From head you can only walk forward one node at a time.

InvariantBefore changing a pointer, save the node it pointed to, and the list never breaks.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 203, with it.

Python
class ListNode:
    def __init__(self, val=0, next=None):
        self.val, self.next = val, next


def reverse(head):
    prev = None
    while head:
        nxt = head.next  # save it before rewiring
        head.next = prev
        prev, head = head, nxt
    return prev


def middle(head):
    """Middle node; the second of the two middles for even lengths."""
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
    return slow
C++
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int v, ListNode* n = nullptr) : val(v), next(n) {}
};

ListNode* reverseList(ListNode* head) {
    ListNode* prev = nullptr;
    while (head) {
        ListNode* nxt = head->next;  // save it before rewiring
        head->next = prev;
        prev = head;
        head = nxt;
    }
    return prev;
}

// Middle node; the second of the two middles for even lengths.
ListNode* middle(ListNode* head) {
    ListNode *slow = head, *fast = head;
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}
Java
class ListNode {
    int val;
    ListNode next;

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    ListNode reverse(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode nxt = head.next; // save it before rewiring
            head.next = prev;
            prev = head;
            head = nxt;
        }
        return prev;
    }

    // Middle node; the second of the two middles for even lengths.
    ListNode middle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}
Go
type ListNode struct {
	Val  int
	Next *ListNode
}

func reverse(head *ListNode) *ListNode {
	var prev *ListNode
	for head != nil {
		next := head.Next // save it before rewiring
		head.Next = prev
		prev, head = head, next
	}
	return prev
}

// middle returns the middle node; the second of the two middles for even lengths.
func middle(head *ListNode) *ListNode {
	slow, fast := head, head
	for fast != nil && fast.Next != nil {
		slow, fast = slow.Next, fast.Next.Next
	}
	return slow
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Dummy head and a tail pointer to splice a new listO(m + n) time · O(1) space

When a new list is spliced together on the way (merging, partitioning, adding numbers, deleting): start from a dummy node and only ever append at a tail pointer, so the head needs no special case, then return dummy.next. LC 21 (Merge Two Sorted Lists), LC 2 (Add Two Numbers) and LC 86 (Partition List) have this shape.

Python
class ListNode:
    def __init__(self, val=0, next=None):
        self.val, self.next = val, next


def merge_two(a, b):
    """One sorted list from two, reusing their nodes."""
    dummy = tail = ListNode()  # a placeholder head: the first node needs no special case
    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  # whatever is left is sorted already
    return dummy.next
C++
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int v, ListNode* n = nullptr) : val(v), next(n) {}
};

// One sorted list from two, reusing their nodes.
ListNode* mergeTwo(ListNode* a, ListNode* b) {
    ListNode dummy(0);  // a placeholder head: the first node needs no special case
    ListNode* tail = &dummy;
    while (a && b) {
        ListNode*& smaller = a->val <= b->val ? a : b;
        tail->next = smaller;
        smaller = smaller->next;
        tail = tail->next;
    }
    tail->next = a ? a : b;  // whatever is left is sorted already
    return dummy.next;
}
Java
class ListNode {
    int val;
    ListNode next;

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    // One sorted list from two, reusing their nodes.
    ListNode mergeTwo(ListNode a, ListNode b) {
        ListNode dummy = new ListNode(0, null), tail = dummy; // the first node needs no special case
        while (a != null && b != null) {
            if (a.val <= b.val) {
                tail.next = a;
                a = a.next;
            } else {
                tail.next = b;
                b = b.next;
            }
            tail = tail.next;
        }
        tail.next = a != null ? a : b; // whatever is left is sorted already
        return dummy.next;
    }
}
Go
type ListNode struct {
	Val  int
	Next *ListNode
}

// mergeTwo returns one sorted list from two, reusing their nodes.
func mergeTwo(a, b *ListNode) *ListNode {
	dummy := &ListNode{} // a placeholder head: the first node needs no special case
	tail := dummy
	for a != nil && b != nil {
		if a.Val <= b.Val {
			tail.Next, a = a, a.Next
		} else {
			tail.Next, b = b, b.Next
		}
		tail = tail.Next
	}
	if a != nil { // whatever is left is sorted already
		tail.Next = a
	} else {
		tail.Next = b
	}
	return dummy.Next
}
Reverse in groups of kO(n) time · O(1) space

To reverse one segment or the list group by group: prev waits before the group, count k nodes first (fewer stay as they are), reverse the group in place, reconnect both ends, and move prev to the group's new tail. LC 25 (Reverse Nodes in k-Group), LC 24 (Swap Nodes in Pairs, k = 2) and LC 92 (Reverse Linked List II) share this skeleton.

Python
class ListNode:
    def __init__(self, val=0, next=None):
        self.val, self.next = val, next


def reverse_k_group(head, k: int):
    """Reverses every full group of k nodes; a shorter tail stays as it is (LC 25)."""
    dummy = ListNode(0, head)
    prev = dummy  # the node before the group being reversed
    while True:
        tail = prev
        for _ in range(k):  # is there a full group after prev?
            tail = tail.next
            if not tail:
                return dummy.next
        nxt, cur, p = tail.next, prev.next, tail.next
        while cur is not nxt:  # reverse prev.next..tail, hanging it onto nxt
            cur.next, p, cur = p, cur, cur.next
        first = prev.next  # the group's old first node is now its last
        prev.next = tail
        prev = first
C++
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int v, ListNode* n = nullptr) : val(v), next(n) {}
};

// Reverses every full group of k nodes; a shorter tail stays as it is (LC 25).
ListNode* reverseKGroup(ListNode* head, int k) {
    ListNode dummy(0, head);
    ListNode* prev = &dummy;  // the node before the group being reversed
    while (true) {
        ListNode* tail = prev;
        for (int i = 0; i < k; i++) {  // is there a full group after prev?
            tail = tail->next;
            if (!tail) return dummy.next;
        }
        ListNode *nxt = tail->next, *cur = prev->next, *p = nxt;
        while (cur != nxt) {  // reverse prev->next..tail, hanging it onto nxt
            ListNode* after = cur->next;
            cur->next = p;
            p = cur;
            cur = after;
        }
        ListNode* first = prev->next;  // the group's old first node is now its last
        prev->next = tail;
        prev = first;
    }
}
Java
class ListNode {
    int val;
    ListNode next;

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    // Reverses every full group of k nodes; a shorter tail stays as it is (LC 25).
    ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0, head);
        ListNode prev = dummy; // the node before the group being reversed
        while (true) {
            ListNode tail = prev;
            for (int i = 0; i < k; i++) { // is there a full group after prev?
                tail = tail.next;
                if (tail == null) return dummy.next;
            }
            ListNode nxt = tail.next, cur = prev.next, p = nxt;
            while (cur != nxt) { // reverse prev.next..tail, hanging it onto nxt
                ListNode after = cur.next;
                cur.next = p;
                p = cur;
                cur = after;
            }
            ListNode first = prev.next; // the group's old first node is now its last
            prev.next = tail;
            prev = first;
        }
    }
}
Go
type ListNode struct {
	Val  int
	Next *ListNode
}

// reverseKGroup reverses every full group of k nodes; a shorter tail stays as it is (LC 25).
func reverseKGroup(head *ListNode, k int) *ListNode {
	dummy := &ListNode{0, head}
	prev := dummy // the node before the group being reversed
	for {
		tail := prev
		for i := 0; i < k; i++ { // is there a full group after prev?
			tail = tail.Next
			if tail == nil {
				return dummy.Next
			}
		}
		next, cur, p := tail.Next, prev.Next, tail.Next
		for cur != next { // reverse prev.Next..tail, hanging it onto next
			cur.Next, p, cur = p, cur, cur.Next
		}
		first := prev.Next // the group's old first node is now its last
		prev.Next = tail
		prev = first
	}
}

Why it works

  1. Reversal invariant: prev heads the reversed part and cur heads the untouched part, and the two are disconnected. Each step saves cur.next, points cur at prev and moves both forward, keeping the invariant; when cur is null, prev is the new head.
  2. Fast and slow pointers on a cycle: once both are inside it, the fast pointer gains one node per step, so the gap shrinks by one each step (mod the cycle length) and they meet within one lap; with no cycle the fast pointer reaches null first.
  3. A dummy node makes deleting the head the same operation as deleting any other node: every real node has a predecessor, so there is no special case.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
链表题我先想清楚指针改动的顺序。反转时维护 prev 和 cur:先存下 cur.next,再把 cur 指回 prev,然后两个指针一起前进,cur 为空时 prev 就是新头。可能删头或换头时加一个哑节点,所有真实节点都有前驱,省掉特判。判环或找中点用快慢指针,进环后快指针每步追近一格,一定会相遇。都是 O(n) 时间、O(1) 空间。
English
For linked lists I first fix the order of pointer changes. To reverse, I keep prev and cur: save cur.next, point cur back at prev, then advance both, and when cur is null prev is the new head. When the head might change I add a dummy node so every real node has a predecessor. For cycles and midpoints I use fast and slow pointers, and inside a cycle the fast one closes the gap by one node per step, so they must meet.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

4 questions
  1. After Floyd's tortoise and hare (slow moves 1, fast moves 2) meet inside a cycle, how do you find the node where the cycle starts?
  2. A singly linked list keeps both head and tail pointers. Which operation is not O(1)?
  3. Linked-list solutions often put a dummy node before the head. What is it for?
  4. The list has n nodes. What is the time complexity of suffix_lengths?
    def length(node):
        n = 0
        while node:
            n += 1
            node = node.next
        return n
    
    def suffix_lengths(head):
        out = []
        while head:
            out.append(length(head))
            head = head.next
        return out

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val, self.next = val, next

    return slow

Practice by stage

This stop's 27 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 6

#ProblemApproachRating
203Remove Linked List ElementsUse a dummy node to unify head and interior deletions while maintaining the predecessor pointer.
206Reverse Linked ListReverse a linked list iteratively, saving the successor before changing each pointer.
21Merge Two Sorted ListsMerge two sorted linked lists, handling empty inputs and remaining tails.
876Middle of the Linked ListLocate the midpoint with slow and fast pointers, distinguishing stopping conditions for odd and even lengths.Rating 1232
83Remove Duplicates from Sorted ListExploit sorted order to deduplicate in place while preserving links between retained nodes.
141Linked List CycleDetect a cycle with slow and fast pointers, using a meeting rather than reaching the end as the termination condition.

Core 16

#ProblemApproachRating
160Intersection of Two Linked ListsSwitch the two pointers to the opposite heads to cancel length differences and detect intersection by node identity.
19Remove Nth Node From End of ListDelete the nth node from the end using pointers a fixed distance apart, including deletion of the head.
82Remove Duplicates from Sorted List IIRemove all nodes with repeated values rather than retaining one, keeping the predecessor of each duplicate run.
328Odd Even Linked ListSplit nodes by odd and even positions, then reconnect the chains without creating a tail cycle.
86Partition ListPartition a linked list stably, preserving internal order on both sides and disconnecting obsolete links.
24Swap Nodes in PairsSwap adjacent pairs locally, reconnecting the predecessor, current pair, and successor completely.
92Reverse Linked List IIReverse only the requested interval and reconnect it to both surrounding portions.
61Rotate ListTurn rotation into forming a cycle and breaking it, handling k larger than the list length.
142Linked List Cycle IIDerive the cycle entry from the slow-fast meeting point using distances around the cycle.
234Palindrome Linked ListFind the midpoint and reverse the second half to test a palindrome, considering restoration of the original structure.
143Reorder ListCombine midpoint detection, reversal, and alternating merge without losing unprocessed nodes.
2Add Two NumbersSimulate addition digit by digit, uniformly handling different lengths and a final carry.
445Add Two Numbers IIUse stacks to add lists with the most significant digit first without requiring changes to the original lists.
138Copy List with Random PointerCopy a random-pointer list using node mappings and an understanding of original-object identity.
147Insertion Sort ListImplement insertion sort on a linked list, maintaining the sorted region and locating insertion positions.
708Insert into a Sorted Circular Linked List 🔒Find an insertion point in a sorted circular list, handling the maximum-to-minimum break and all-equal nodes.

Advanced 5

#ProblemApproachRating
430Flatten a Multilevel Doubly Linked ListFlatten a multilevel doubly linked list while maintaining next, prev, child, and reconnection positions.
148Sort ListApply merge sort to a linked list, practicing splitting and merging while explaining O(n log n) complexity.
23Merge k Sorted ListsMerge multiple sorted lists with a min-heap or divide and conquer, analyzing the effects of node count and list count.
25Reverse Nodes in k-GroupReverse groups of k nodes while leaving a shorter final group unchanged and maintaining group boundaries.
1171Remove Zero Sum Consecutive Nodes from Linked ListUse repeated prefix sums to locate and remove consecutive linked-list nodes whose sum is zero.Rating 1782

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.