Reverse a Linked List
Given the head
Example 1
Output: [5, 4, 3, 2, 1]
Example 2
Output: [2, 1]
Example 3
Output: []
Solution 1 - Iterative Approach
The key idea is to traverse the list and reverse the nextprevcurrnext
- Initialize
andprev = null .curr = head - While
is not null, savecurr in a temporary variable, then pointcurr.next tocurr.next .prev - Advance
toprev andcurr to the saved next node.curr - After the loop,
is the new head of the reversed list.prev
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next; // save next
curr.next = prev; // reverse pointer
prev = curr; // move prev forward
curr = next; // move curr forward
}
return prev; // prev is now the new head
}
}
Complexity Analysis:
Time complexity: O(n) where n is the number of nodes in the linked list, since we visit each node once.
Space complexity: O(1) as we only use a constant number of pointers.
Solution 2 - Recursive Approach
In the recursive approach, we recurse to the end of the list and then fix the pointers on the way back.
- Base case: if
orhead == null , returnhead.next == null (it is the new head).head - Recursively reverse the rest of the list starting from
.head.next - After the recursive call returns,
is the last node of the reversed sublist. Sethead.next to make it point back to the current node.head.next.next = head - Set
to avoid a cycle and return the new head.head.next = null
public class ReverseLinkedList {
public ListNode reverseListRecursive(ListNode head) {
// Base case: empty list or single node
if (head == null || head.next == null) {
return head;
}
// Reverse the rest of the list
ListNode newHead = reverseListRecursive(head.next);
// Make head.next point back to head
head.next.next = head;
head.next = null;
return newHead;
}
}
Complexity Analysis:
Time complexity: O(n) since every node is visited exactly once through the recursion.
Space complexity: O(n) due to the recursion call stack, which can go n levels deep.