Reverse a Linked List
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
0 ≤ number of nodes in head ≤ 200 - ◆
-1000 ≤ node value ≤ 1000
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Recursive — Reverse the Rest, Then Fix This Node
GoodRecurse all the way to the last node first — that node becomes the new head, and it's returned unchanged back up through every call. As each call returns, it fixes exactly one link: the node just after the current one (which is now the tail of the already- reversed rest) gets its .next pointed back at the current node, and the current node's own .next is cleared so it becomes the new tail. Repeating this on the way back up through every stack frame reverses the whole list, though each frame held on the call stack costs O(n) space for a long list.
O(n)O(n)1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node reverseList(Node head) {
9 if (head == null || head.next == null) return head;
10 Node newHead = reverseList(head.next);
11 head.next.next = head;
12 head.next = null;
13 return newHead;
14 }
15}Iterative — Three Pointers, Single Pass
OptimalWalk the list once, carrying two pointers: prev (the reversed portion built so far, starting empty) and curr (the next node to absorb into it). At each node, save curr.next before overwriting it — otherwise the rest of the list would be lost — then point curr.next back at prev, and slide both prev and curr forward by one. Once curr runs off the end, prev is sitting on the last node visited, which is now the new head of the fully reversed list.
O(n)O(1)1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node reverseList(Node head) {
9 Node prev = null;
10 Node curr = head;
11 while (curr != null) {
12 Node next = curr.next;
13 curr.next = prev;
14 prev = curr;
15 curr = next;
16 }
17 return prev;
18 }
19}