206. Reverse Linked List
| Attempt | Time Required |
|---|---|
| For notes | 22 min 46 sec |
Question
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: []
Constraints:
- The number of nodes in the list is the range
[0, 5000]. -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
Approach 1: Brute Force
Intuition
- Stack: Last In First Out (LIFO)
Algorithm
- Create a
stack<int> sto hold the values of the linkedlist. - Declare
ListNode* curr& initialize withhead. - Loop through the LL using
currpushing value of each node into the stack. - Reinitialize
curr = head - Loop through the LL again replacing the value of
currwith the value at the top of the stack & pop the stack. - Return the
head
Code
class Solution {
public:
ListNode* reverseList(ListNode* head) {
stack<int> s;
ListNode* curr = head;
while (curr) {
s.push(curr->val);
curr = curr->next;
}
curr = head;
while (curr) {
int newVal = s.top();
s.pop();
curr->val = newVal;
curr = curr->next;
}
return head;
}
};
Complexity Analysis
- Time Complexity:
- Space Complexity:
(Stack space)
Approach 2: Optimal 1 (iterative)
Intuition
- Changing the links in-place
Algorithm
- Declare & initialize
ListNode* curr = head. - Declare & initialize
ListNode* prev = NULL. - Loop through the LL till
curr != NULL.- Declare & initialize
ListNode* next = curr->next;so the reference for the next node is not lost when we change the links. curr->nextwill point toprevprevwill now becurrcurrwill now benext
- Declare & initialize
- Now,
curr == NULL, butprevwill point to the last node which will be the new head. - Return
prev.
Code
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
Complexity Analysis
- Time Complexity:
- Space Complexity:
Approach 3: Optimal (Recursive)
Algorithm
- Base case:
if (head == NULL || head->next == NULL) return head. - Declare & initialize
ListNode* newHeadwith recursive call forhead->next. - Reverse the link,
head->next->next = head. head->next = NULL.- Return
newHead.
Code
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};
Complexity Analysis
- Time Complexity:
- Space Complexity: