Reverse a Linked List
Problem Statement:β
Given theΒ headΒ of a singly linked list, reverse the list, and returnΒ the reversed list.
Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:

Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
-
Example:
β Solution: Iterativeβ
class Solution {
public:
Node* reverseList(struct Node* head) {
Node *next, *prev = NULL, *curr = head;
while(curr != NULL){
next = curr->next; // store next node
curr->next = prev; // reverse the link
prev = curr; // move prev forward
curr = next; // move curr forward
}
return prev; // new head
}
};
β Solution: Recursiveβ
class Solution {
public:
Node* reverseList(struct Node* head) {
if(head == NULL || head->next == NULL){
return head; // base case
}
Node *new_node = reverseList(head->next); // reverse rest of list
head->next->next = head; // set next nodeβs next to current
head->next = NULL; // break original link
return new_node; // new head of reversed list
}
};
π How It Worksβ
π Iterativeβ
- Initialize
prev = NULL,curr = head. - At each step:
- Store next node.
- Reverse current nodeβs link.
- Advance
prevandcurr.
- Finally,
prevwill point to the new head.
π Recursiveβ
- Go to the end using recursion.
- On backtracking, reverse the links.
- Base case: when
head == NULLorhead->next == NULL.
π§© Key Logicβ
Iterative:β
curr->next = prev
Recursive:β
head->next->next = head
head->next = NULL
β±οΈ Time & Space Complexityβ
| Approach | Time | Space |
|---|---|---|
| Iterative | O(N) | O(1) |
| Recursive | O(N) | O(N) (stack) |
β οΈ Edge Casesβ
- Empty list β returns
NULL - Single node β returns the same node
- Already reversed β still works correctly
π‘ Other Approachesβ
| Method | Notes |
|---|---|
| Using Stack | Extra space O(N), simpler |
| Tail Recursion | Space optimization possible with language support |
π Related Problemsβ
- Reverse a Linked List II (between positions m and n)
- Palindrome Linked List
- Add Two Numbers (Reverse-style processing)
- Detect Cycle in Linked List
π¬