01
Problem Statement
Given the head of a singly linked list, reverse the list and return the new head. The list has next pointers only; we must reverse the direction of the next pointers in place (or with O(1) extra space).
- Empty list: return null. Single node: return that node. The classic approach is iterative with three pointers:
prev,curr, and a savednext.
02
Key Observations
- Iterative: Start with
prev = null,curr = head. In each step: savenext = curr.next, setcurr.next = prev(reverse the link), thenprev = curr,curr = next. Whencurrbecomes null,previs the new head. Each node is visited once; we only changenextto point backward. - Recursive: Reverse the sublist
head.nextand get its new head; then sethead.next.next = headandhead.next = null. Return the new head of the reversed rest (which is the new overall head). Base: ifhead == null || head.next == null, returnhead.
03
Approach
High-level: prev = null, curr = head. While curr != null: next = curr.next, curr.next = prev, prev = curr, curr = next. Return prev.
Steps:
ListNode prev = null, curr = head. Whilecurr != null:ListNode next = curr.next;curr.next = prev;prev = curr;curr = next.- Return
prev.
04
Implementation
Java
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}05
Test Cases
Example 1
Input
head = [1,2,3,4,5]
Expected
[5,4,3,2,1]Explanation
Reversed.
06
Complexity Analysis
- Time: O(n).
- Space: O(1) iterative.
07
Follow-ups
- Reverse linked list II: reverse only a sublist.