Here’s the question link on Leetcode 206. Reverse Linked List:
https://leetcode.com/problems/reverse-linked-list/description
Contents
Brute Force – Using a Stack
We can store all the node values in a stack.
Since a stack follows LIFO (Last In, First Out), we’ll get the values in reverse order.
Then, we can traverse the linked list again and replace its values using the stack.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
stack<int> st;
ListNode* temp = head;
while(temp != NULL) {
st.push(temp->val);
temp = temp->next;
}
temp = head;
while(temp != NULL) {
temp->val = st.top();
st.pop();
temp = temp->next;
}
return head;
}
};
Optimal – Iterative Approach
Instead of using extra space, we can reverse the links between nodes directly.
We’ll maintain three pointers:
prev– Previous node, initiallyNULL.curr– Current node.next– Stores the next node so we don’t lose the remaining list.
For every node, point it backwards towards prev and move all three pointers forward.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while(curr != NULL) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
Bonus – Recursive Approach
We can also reverse the list using recursion.
First, reach the last node. Then, while returning from recursion, reverse the links.
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;
}
};