Reverse a Linked List
Turn every link of a singly linked list around, so the last node becomes the new head.
Given the head (first node) of a singly linked list, reverse the list so that its nodes come in the opposite order, and return the head of the reversed list.
Example 1
Output: [5, 4, 3, 2, 1]
Example 2
Output: [2, 1]
Example 3
Output: []
The Idea
Think of a treasure hunt where each clue only tells you where the next clue is hidden. A singly linked list works the same way. Each piece is called a node, and it holds a value and a link, named nextnextnull
Look at Example 1. The head holds 1, its nextnextnull
Turning a link has a catch. A node's nextprevcurrnext
The row labelled "start" is Example 1 as given. In the row labelled "after turning 1 and 2", 1 points to nullprevcurr
Before that arrow is turned, nextprevcurrcurrnullprev
So reversing a list is a single walk from the head to the end: prevcurrnext
Solution Approach
Turning that idea into code means settling three things: where the three variables start, the order of the moves for each node, and when to stop. A recursive version, shown last, is an optional alternative.
Where the variables start
Why not copy the values into an array and write them back in reverse? That works, but it needs an extra array as long as the list and two passes over it. Turning the links needs only the three variables.
Before anything is turned, the turned part is empty, so prevnullcurrprevnextnull
The order of the moves
What happens to each node, and in which order? Four assignments: save curr.nextnextcurr.nextprevprevcurrcurrnextcurr.nextprevcurr
When to stop
When is every node turned? When currnullprevcurrnullprevnull
A recursive version (optional)
Can the reversal be written without a loop? A method that calls itself on a smaller part of the input is called recursive. Here, reverseRecursive(head)headhead.next
When the call for [1, 2, 3]headhead.next.next = headhead.next = nullhead.next = null3 -> 2 -> 1 -> 2 -> 1 -> ...
The recursive version is short, but every call waits for the call after it to finish, so a list of n nodes keeps n calls waiting at once. Java keeps them on the call stack, an area of memory with a fixed size, and a long list can fill it.
Java Solution
The method reverseList
- First, create
asprev , for the empty turned part, andnull ascurr , the first node to turn.head - Loop while
is notcurr . Inside the loop, savenull in a new variable,curr.next .next - Point
atcurr.next , which turns the link of this node.prev - Move
toprev andcurr tocurr , one node further along.next - When the loop ends, return
, the old last node.prev
The class also holds reverseRecursiveListNodebuildshow[5, 4, 3, 2, 1]
The main
public class ReverseLinkedList {
static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next; // remember the rest before cutting the link
curr.next = prev; // point backwards
prev = curr;
curr = next;
}
return prev; // the old tail is the new head
}
public static ListNode reverseRecursive(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseRecursive(head.next); // reverse everything after head
head.next.next = head; // the node after head now points back to it
head.next = null; // the old head becomes the end
return newHead;
}
static ListNode build(int... values) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (int v : values) {
tail.next = new ListNode(v);
tail = tail.next;
}
return dummy.next;
}
static String show(ListNode head) {
StringBuilder sb = new StringBuilder("[");
for (ListNode n = head; n != null; n = n.next) {
sb.append(n.val);
if (n.next != null) {
sb.append(", ");
}
}
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(reverseList(build(1, 2, 3, 4, 5))));
System.out.println(show(reverseList(build(1, 2))));
System.out.println(show(reverseList(build())));
System.out.println(show(reverseList(build(7))));
System.out.println(show(reverseRecursive(build(1, 2, 3, 4, 5))));
int[] big = new int[100000];
for (int i = 0; i < big.length; i++) {
big[i] = i + 1;
}
System.out.println("loop, 100000 nodes: head is " + reverseList(build(big)).val);
try {
System.out.println("recursion, 100000 nodes: head is "
+ reverseRecursive(build(big)).val);
} catch (StackOverflowError e) {
System.out.println("recursion, 100000 nodes: StackOverflowError");
}
}
}
Running it prints:
[5, 4, 3, 2, 1]
[2, 1]
[]
[7]
[5, 4, 3, 2, 1]
loop, 100000 nodes: head is 100000
recursion, 100000 nodes: StackOverflowError
Look at the third line, []currnullprevnull[7]nextnull
The fifth line, [5, 4, 3, 2, 1]reverseRecursiveStackOverflowError
Complexity
Both versions turn each node's link once; they differ in the memory they need while doing it.
- Time: O(n) for both. The loop runs once for each of the n nodes, with four assignments per round, and the recursion makes one call per node.
- Space: O(1) for the loop, O(n) for the recursion. The loop only keeps
,prev andcurr , and reuses the existing nodes. The recursion keeps one waiting call per node on the call stack, which is why the 100,000-node list overflowed it.next
The same loop, applied to only a part of the list, solves