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.
1#include <stdio.h>
2#include <stdlib.h>
3
4struct ListNode {
5 int val;
6 struct ListNode* next;
7};
8
9struct ListNode* reverseList(struct ListNode* head) {
10 struct ListNode* prev = NULL;
11 struct ListNode* curr = head;
12 struct ListNode* nxt = NULL;
13 while (curr != NULL) {
14 nxt = curr->next;
15 curr->next = prev;
16 prev = curr;
17 curr = nxt;
18 }
19 return prev;
20}
In this C implementation, three pointers are utilized: prev
, curr
, and nxt
. Initially, prev
is NULL
while curr
points to the head. A loop runs until curr
is NULL
. Inside the loop, nxt
stores the next node, then curr->next
is set to prev
to reverse the pointer, and prev
is moved to curr
, curr
to nxt
.
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.
1#include <iostream>
2using namespace std;
3
4struct ListNode {
5 int val;
6 ListNode* next;
7 ListNode(int x) : val(x), next(NULL) {}
8};
9
10ListNode* reverseList(ListNode* head) {
11 if (!head || !head->next) return head;
12 ListNode* p = reverseList(head->next);
13 head->next->next = head;
14 head->next = NULL;
15 return p;
16}
This C++ implementation uses recursion to reach the end of the list, then reverses the pointers as the recursive stack unwinds, effectively reversing each connection in the list.