Iterative Approach: This approach involves using a loop to traverse the linked list and reverse the direction of the next
pointers at each step. Start with three pointers: prev
as null
, curr
as the head of the list, and nxt
to temporarily store the next node. In each iteration, change the curr.next
to prev
, move prev
to curr
, and curr
to nxt
. The loop ends when curr
becomes null
, with prev
being the new head.
Time Complexity: O(n), where n is the number of nodes in the linked list because each node is processed once.
Space Complexity: O(1) as it uses only a constant amount of space.
1function ListNode(val, next = null) {
2 this.val = val;
3 this.next = next;
4}
5
6function reverseList(head) {
7 let prev = null;
8 let curr = head;
9 while (curr !== null) {
10 let nxt = curr.next;
11 curr.next = prev;
12 prev = curr;
13 curr = nxt;
14 }
15 return prev;
16}
The JavaScript code also employs the standard iterative mechanism with the help of prev
, curr
, and nxt
pointers, progressively reversing the list until curr
reaches null
.
Recursive Approach: In this method, you move to the end of the list via recursive calls while reversing the next
pointers on the way back. The base case for the recursion is when the list is empty or when it contains only one node. In each call, move to the next node, reverse the rest of the list, use the next
pointer's next
field to point to the current node, and finally return the head of the reversed list.
Time Complexity: O(n), due to n recursive calls.
Space Complexity: O(n), for stack space in recursion.
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class Solution:
7 def reverseList(self, head: ListNode) -> ListNode:
8 if not head or not head.next:
9 return head
10 p = self.reverseList(head.next)
11 head.next.next = head
12 head.next = None
13 return p
The Python recursive solution involves recursively calling the reverse function until reaching the end of the list, then reversing the next
pointers on the return path of the recursion.