Reverse a linked list
34 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
- Start with
Node prev = null;andNode curr = head;. - While
curr != null, save the next node:Node nextTemp = curr.next;. - Flip the arrow backward:
curr.next = prev;. - Step both pointers forward:
prev = curr; curr = nextTemp;. - When
currbecomesnull,prevstands on the new head—return prev;.
Iterative 3-Pointer Reversal on 10 -> 20 -> 30 -> 40
Step 1 of 5
- prev
- null
- curr
- 10
- nextTemp
- 20
Example 1 · Brute force: copy the values into a list and write them back reversed (O(n) time, O(n) extra space)
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)); }}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
valfields 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.
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)
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)); }}Original: 10 -> 20 -> 30 -> 40 -> null Iterative: 40 -> 30 -> 20 -> 10 -> null Recursive: 10 -> 20 -> 30 -> 40 -> null
What this code does
reverseIterativeflips.nextpointers one by one using 3 local variables (O(1) space).reverseRecursiveflips the list back usinghead.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 = headpoints the second node (head.next) back tohead.head.next = nullavoids 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)
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))); }}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 -> 5withleft = 2, right = 4,prestops at1andcurris2. - Step 1 moves
3afterpre(1 -> 3 -> 2 -> 4 -> 5); step 2 moves4afterpre(1 -> 4 -> 3 -> 2 -> 5).
Example 4 · Reverse Nodes in k-Group in O(1) Extra Space
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))); }}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 togroupNext. - When fewer than
knodes remain (4 -> 5fork = 3),kthbecomesnulland the loop stops.
- Reverse Linked List II: Reverse nodes from 1-based position
lefttorightin one pass.
- Create
Node dummy = new Node(0, head)and walkleft - 1steps topre(right beforeleft). - Let
curr = pre.next(the node originally atleft). - Repeat
right - lefttimes: pluckmove = curr.next(curr.next = move.next) and insertmoveright afterpre(move.next = pre.next; pre.next = move;). 2. Reverse Nodes in k-Group: Reverse nodeskat a time, leaving a short final group unchanged. - From
groupPrev = dummy, walkksteps tokth. Ifkth == null, stop. - Reverse
[groupPrev.next .. kth], linkgroupPrev.next = kth, and movegroupPrevto the group's new tail.
Remember:
- Reverse Between:
prestays fixed while eachcurr.nextis moved right afterpre. - Reverse k-Group: check that
knodes remain before reversing so a short final group stays in order.
Next step
Check your understanding
10 quick questions