Given the head of a singly linked list, reverse the list, and return the reversed list.
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Input: head = [1,2]
Output: [2,1]
Input: head = []
Output: []
[0, 5000]-5000 <= Node.val <= 5000The key idea is to reverse the pointers one by one while traversing the list.
prev (initially null), curr (head), and nextcurr is not null:
next = curr.next (before we lose it)curr.next = prevprev = curr, curr = nextprev (new head)Initial: 1 → 2 → 3 → 4 → 5 → null
↑
curr
Step 1: null ← 1 2 → 3 → 4 → 5 → null
↑ ↑
prev curr
Step 2: null ← 1 ← 2 3 → 4 → 5 → null
↑ ↑
prev curr
Step 3: null ← 1 ← 2 ← 3 4 → 5 → null
↑ ↑
prev curr
... continue until curr = null
Final: null ← 1 ← 2 ← 3 ← 4 ← 5
↑
prev (new head)
Recursively reverse the rest of the list, then fix the pointers.
head is null or single node, return headnewHead = reverseList(head.next)head.next.next = headhead.next = nullnewHeadThis problem demonstrates:
1/**
2 * Definition for singly-linked list.
3 */
4class ListNode {
5 int val;
6 ListNode next;
7 ListNode() {}
8 ListNode(int val) { this.val = val; }
9 ListNode(int val, ListNode next) { this.val = val; this.next = next; }
10}
11
12class Solution {
13 // Solution 1: Iterative (Optimal - O(1) space)
14 public ListNode reverseList(ListNode head) {
15 // Use three pointers: prev, curr, next
16 ListNode prev = null;
17 ListNode curr = head;
18
19 // Traverse the list and reverse pointers
20 while (curr != null) {
21 // Save next node before we lose it
22 ListNode next = curr.next;
23
24 // Reverse the pointer
25 curr.next = prev;
26
27 // Move pointers forward
28 prev = curr;
29 curr = next;
30 }
31
32 // prev is now the new head
33 return prev;
34 }
35
36 // Solution 2: Recursive
37 public ListNode reverseListRecursive(ListNode head) {
38 // Base cases
39 if (head == null || head.next == null) {
40 return head;
41 }
42
43 // Recursively reverse the rest of the list
44 ListNode newHead = reverseListRecursive(head.next);
45
46 // Fix the pointers
47 // head.next is now the last node in reversed portion
48 // Make it point back to current head
49 head.next.next = head;
50
51 // Current head is now the tail, point to null
52 head.next = null;
53
54 return newHead;
55 }
56}
57