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.
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 prev = None
9 curr = head
10 while curr:
11 nxt = curr.next
12 curr.next = prev
13 prev = curr
14 curr = nxt
15 return prev
In the Python implementation, prev
, curr
, and nxt
pointers again maintain the structure necessary for iterative reversal. After resetting pointers, the head is reassigned to prev
, which is the new head of the reversed list.
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 int val;
3 ListNode next;
4 ListNode() {}
5 ListNode(int val) { this.val = val; }
6 ListNode(int val, ListNode next) { this.val = val; this.next = next; }
7}
8
9public class Solution {
10 public ListNode reverseList(ListNode head) {
11 if (head == null || head.next == null) return head;
12 ListNode p = reverseList(head.next);
13 head.next.next = head;
14 head.next = null;
15 return p;
16 }
17}
In Java, the recursive function continues traversing until it reaches the list's last node, then starts reversing pointers until reaching the original head. Each recursive call returns the new head of the reversed sublist.