Skip to lesson

Reverse a linked list

Reversing a linked list in place flips every next arrow so the tail becomes the new head. This three-pointer loop also powers Palindrome Linked List, Reorder List, and Reverse Nodes in k-Group.

Three-pointer iterative reverse

Copying the values into an ArrayList and writing them back reversed costs O(n) extra space. Flipping the arrows themselves (1 -> 2 -> 3 -> null becomes null <- 1 <- 2 <- 3) needs only O(1) extra space.

  1. Start with Node prev = null; and Node curr = head;.
  2. While curr != null, save the next node: Node nextTemp = curr.next;.
  3. Flip the arrow backward: curr.next = prev;.
  4. Step both pointers forward: prev = curr; curr = nextTemp;.
  5. When curr becomes null, prev stands on the new head—return prev;.

Iterative 3-Pointer Reversal on 10 -> 20 -> 30 -> 40

Step 1 of 5

10curr20nextTemp3040
prev
null
curr
10
nextTemp
20
Start with prev = null and curr = 10. Save nextTemp = curr.next (20) before flipping 10's pointer.

Example 1 · Brute force: copy the values into a list and write them back reversed (O(n) time, O(n) extra space)

ReverseByCopyDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ReverseByCopyDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    static void reverseValues(Node head) {        List<Integer> values = new ArrayList<>();        for (Node curr = head; curr != null; curr = curr.next) {            values.add(curr.val);        }        int i = values.size() - 1;        for (Node curr = head; curr != null; curr = curr.next) {            curr.val = values.get(i--);        }    }
    static String show(Node head) {        StringBuilder sb = new StringBuilder();        for (Node curr = head; curr != null; curr = curr.next) {            sb.append(curr.val).append(" -> ");        }        return sb.append("null").toString();    }
    public static void main(String[] args) {        Node head = new Node(10, new Node(20, new Node(30, new Node(40, null))));        System.out.println("Before: " + show(head));        reverseValues(head);        System.out.println("After:  " + show(head));    }}
Output
Before: 10 -> 20 -> 30 -> 40 -> null
After:  40 -> 30 -> 20 -> 10 -> null

What this code does

  • The first loop copies every value into an ArrayList, and the second loop writes the values back from the end, so the list holds n extra numbers: O(n) extra space.
  • No arrow changes; only the val fields are overwritten. The nodes keep their places, which is not acceptable when other code holds references to specific nodes.
  • Flipping the arrows themselves, shown in the next example, gives the same result with O(1) extra space.

At each node curr, point curr.next backward to prev. Writing curr.next = prev; right away would lose the rest of the list, so a third pointer nextTemp saves curr.next first. Practise the four lines of the loop in the right order:

Order of execution

Order the four lines of the loop

Tap the lines in the order they run for each node.

while (curr != null) {
// four lines go here
}
return prev;
Trace on 1 -> 2 -> null: start prev = null, curr = 1. Step 1 sets 1.next = null, prev = 1, curr = 2. Step 2 sets 2.next = 1, prev = 2, curr = null and returns prev (2 -> 1 -> null).

Recursive reverse

To reverse head recursively, assume Node newHead = reverseRecursive(head.next); has already reversed the rest of the list (2 <- 3 <- ... <- newHead).

Example 2 · Optimal: three-pointer iterative reverse (O(n) time, O(1) space) and recursive reverse (O(n) call stack)

ReverseListDemo.javaJava
public class ReverseListDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    public static Node reverseIterative(Node head) {        Node prev = null;        Node curr = head;        while (curr != null) {            Node nextTemp = curr.next;            curr.next = prev;            prev = curr;            curr = nextTemp;        }        return prev;    }
    public static Node reverseRecursive(Node head) {        if (head == null || head.next == null) {            return head;        }        Node newHead = reverseRecursive(head.next);        head.next.next = head;        head.next = null;        return newHead;    }
    static String format(Node head) {        StringBuilder sb = new StringBuilder();        for (Node c = head; c != null; c = c.next) sb.append(c.val).append(" -> ");        return sb.append("null").toString();    }
    public static void main(String[] args) {        Node list = new Node(10, new Node(20, new Node(30, new Node(40, null))));        System.out.println("Original:  " + format(list));        list = reverseIterative(list);        System.out.println("Iterative: " + format(list));        list = reverseRecursive(list);        System.out.println("Recursive: " + format(list));    }}
Output
Original:  10 -> 20 -> 30 -> 40 -> null
Iterative: 40 -> 30 -> 20 -> 10 -> null
Recursive: 10 -> 20 -> 30 -> 40 -> null

What this code does

  • reverseIterative flips .next pointers one by one using 3 local variables (O(1) space).
  • reverseRecursive flips the list back using head.next.next = head; head.next = null; as calls return.

In 1 -> 2 <- 3, head (1) still points to 2 (head.next), and 2.next is null. To make 2 point back to 1, write: ``java head.next.next = head; // makes 2.next point back to 1 head.next = null; // breaks 1 -> 2 so 1 becomes the new tail return newHead; ` Base case: when head == null || head.next == null, return head`. Time is O(n) and call-stack space is O(n).

Three rules of the recursive step:

  • head.next.next = head points the second node (head.next) back to head.
  • head.next = null avoids a 2-node cycle (1 <-> 2) at the new tail.
  • newHead (the old tail) is returned unchanged up the call stack.

Reverse a sublist and reverse in groups of k

Two common problems reverse only part of a list in place (shown after the code).

Example 3 · Reverse Linked List II (Sublist from left to right)

ReverseSublistDemo.javaJava
public class ReverseSublistDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    public static Node reverseBetween(Node head, int left, int right) {        Node dummy = new Node(0, head);        Node pre = dummy;        for (int i = 1; i < left; i++) {            pre = pre.next;        }        Node curr = pre.next; // First node of the sublist        for (int i = 0; i < right - left; i++) {            Node move = curr.next;            curr.next = move.next;            move.next = pre.next;            pre.next = move;        }        return dummy.next;    }
    static String format(Node head) {        StringBuilder sb = new StringBuilder();        for (Node c = head; c != null; c = c.next) sb.append(c.val).append(" -> ");        return sb.append("null").toString();    }
    public static void main(String[] args) {        Node head = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null)))));        System.out.println("Reverse [2..4]: " + format(reverseBetween(head, 2, 4)));
        Node head2 = new Node(10, new Node(20, new Node(30, null)));        System.out.println("Reverse [1..2]: " + format(reverseBetween(head2, 1, 2)));    }}
Output
Reverse [2..4]: 1 -> 4 -> 3 -> 2 -> 5 -> null
Reverse [1..2]: 20 -> 10 -> 30 -> null

What this code does

  • On 1 -> 2 -> 3 -> 4 -> 5 with left = 2, right = 4, pre stops at 1 and curr is 2.
  • Step 1 moves 3 after pre (1 -> 3 -> 2 -> 4 -> 5); step 2 moves 4 after pre (1 -> 4 -> 3 -> 2 -> 5).

Example 4 · Reverse Nodes in k-Group in O(1) Extra Space

ReverseKGroupDemo.javaJava
public class ReverseKGroupDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    public static Node reverseKGroup(Node head, int k) {        Node dummy = new Node(0, head);        Node groupPrev = dummy;
        while (true) {            Node kth = groupPrev;            for (int i = 0; i < k && kth != null; i++) {                kth = kth.next;            }            if (kth == null) break; // Fewer than k nodes left!
            Node groupNext = kth.next;            Node prev = groupNext;            Node curr = groupPrev.next;            while (curr != groupNext) {                Node tmp = curr.next;                curr.next = prev;                prev = curr;                curr = tmp;            }
            Node newGroupTail = groupPrev.next;            groupPrev.next = kth;            groupPrev = newGroupTail;        }        return dummy.next;    }
    static String format(Node head) {        StringBuilder sb = new StringBuilder();        for (Node c = head; c != null; c = c.next) sb.append(c.val).append(" -> ");        return sb.append("null").toString();    }
    public static void main(String[] args) {        Node a = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null)))));        System.out.println("k = 2: " + format(reverseKGroup(a, 2)));
        Node b = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null)))));        System.out.println("k = 3: " + format(reverseKGroup(b, 3)));    }}
Output
k = 2: 2 -> 1 -> 4 -> 3 -> 5 -> null
k = 3: 3 -> 2 -> 1 -> 4 -> 5 -> null

What this code does

  • Starting with Node prev = groupNext; links the new tail of the reversed group directly to groupNext.
  • When fewer than k nodes remain (4 -> 5 for k = 3), kth becomes null and the loop stops.
  1. Reverse Linked List II: Reverse nodes from 1-based position left to right in one pass.
  • Create Node dummy = new Node(0, head) and walk left - 1 steps to pre (right before left).
  • Let curr = pre.next (the node originally at left).
  • Repeat right - left times: pluck move = curr.next (curr.next = move.next) and insert move right after pre (move.next = pre.next; pre.next = move;). 2. Reverse Nodes in k-Group: Reverse nodes k at a time, leaving a short final group unchanged.
  • From groupPrev = dummy, walk k steps to kth. If kth == null, stop.
  • Reverse [groupPrev.next .. kth], link groupPrev.next = kth, and move groupPrev to the group's new tail.

Remember:

  • Reverse Between: pre stays fixed while each curr.next is moved right after pre.
  • Reverse k-Group: check that k nodes remain before reversing so a short final group stays in order.

Next step

Check your understanding

10 quick questions