Reverse Linked List
Reverse Linked List is a easy linked list problem solved with the front middle back pointer pattern.
The best approach, optimal (iterative, prev / cur / next), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, from recursive up.
Problem
Reverse a singly linked list and return the new head.
Examples
Example 1
- Input
head = [1, 2, 3, 4]- Output
[4, 3, 2, 1]
Example 2
- Input
head = []- Output
[]
Constraints
- The list has
0to5000nodes.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
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
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Recursive | O(n) | O(n) |
| Optimal (iterative, prev / cur / next) | O(n) | O(1) |
1Recursive
O(n)O(n)Recursion depth n.Reverse the rest of the list, then make the next node point back at the current one.
- If head or head.next is null, return head.
- newHead = reverse(head.next); head.next.next = head; head.next = null.
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}2Optimal (iterative, prev / cur / next)
O(n)O(1)Walk the list flipping each link backward. Save next before overwriting cur.next so you can keep going.
- prev = null, cur = head.
- next = cur.next; cur.next = prev; prev = cur; cur = next.
- Return prev.
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null, cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}Edge cases to test
- Empty list or one node
Hints
Hint 1
Three pointers: previous, current and the saved next node, so you never lose the rest of the list.
FAQ
What is the best time complexity for Reverse Linked List?
Optimal (iterative, prev / cur / next) runs in O(n) time and O(1) extra space.
Which pattern does Reverse Linked List use?
It is a linked list problem that uses the front middle back pointer pattern. Other problems with the same pattern: Reverse Linked List II, Reverse Nodes in k-Group, Palindrome Linked List.
Is there a brute force solution for Reverse Linked List?
Yes. Recursive takes O(n) time and O(n) space. Reverse the rest of the list, then make the next node point back at the current one.
Which edge cases should I test for Reverse Linked List?
Empty list or one node.