Given the
Output: [5, 4, 3, 2, 1]
Output: [2, 1]
Output: []
Contents
Solution 1 - Iterative approach Solution 2 - Recursive approach
The key idea is to traverse the list and reverse the
- Initialize
prev = null andcurr = head . - While
curr is not null, savecurr.next in a temporary variable, then pointcurr.next toprev . - Advance
prev tocurr andcurr to the saved next node. - After the loop,
prev is the new head of the reversed list.
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.
In the recursive approach, we recurse to the end of the list and then fix the pointers on the way back.
- Base case: if
head == null orhead.next == null , returnhead (it is the new head). - Recursively reverse the rest of the list starting from
head.next . - After the recursive call returns,
head.next is the last node of the reversed sublist. Sethead.next.next = head to make it point back to the current node. - Set
head.next = null to avoid a cycle and return the new head.
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.