Linked List · Pattern 4 of 5

In-place reversal: prev, curr and next

Walk the list with three pointers: save next, point curr back at prev, then step both forward. The same loop reverses the whole list, one part of it, or k nodes at a time, in O(1) space.

3 variations · 4 problems · 4 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Reverse the whole list or a range of positions
  • Reverse in groups of k
  • Compare the list with itself backwards (palindrome)
  • O(1) extra space, so no stack

The template

Front Middle Back Pointer
ListNode reverseList(ListNode head) {
    ListNode prev = null, curr = head;
    while (curr != null) {
        ListNode next = curr.next;               // save before rewiring
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev;                                 // the old tail is the new head
}

// reverse positions left..right (1-indexed)
ListNode reverseBetween(ListNode head, int left, int right) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode before = dummy;
    for (int i = 1; i < left; i++) before = before.next;   // the node before the part
    ListNode prev = null, curr = before.next;
    for (int i = left; i <= right; i++) {
        ListNode next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    before.next.next = curr;                     // the part's old first node is now its last
    before.next = prev;                          // and its old last node is now its first
    return dummy.next;
}

The variations

  1. 1Reverse the whole list

    Three pointers, four lines in the loop: save next, point back, move prev, move curr. When curr is null, prev is the new head.

  2. 2Reverse a part and reconnect

    Stop on the node before the part (a dummy helps when the part starts at the head), reverse exactly the nodes you need, then stitch both ends back. For k-groups, first check that k nodes are left, then repeat the same step group by group.

  3. 3Reverse half and compare

    Find the middle with fast and slow pointers, reverse the second half, then walk both halves together comparing values. That checks a palindrome in O(1) space.

Mistakes to avoid

  • Writing curr.next = prev before saving curr.next: the rest of the list is lost.
  • Returning head (now the tail) instead of prev.
  • Reversing a part but forgetting to reconnect both ends: the node before the part and the node after it.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.