206. Reverse Linked List
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Linked List
- Time
- O(N)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven the head of a singly linked list, reverse all the node pointers so that the last node becomes the new head and return it.
Approach
- Use three pointers (
prev,curr,next) to perform an in-place reversal in a single pass. - At each step, save the next node, flip
curr->nextto point backward atprev, then advance bothprevandcurrforward. - When
currbecomes null the entire list has been reversed andprevholds the new head. - This works because each node's forward link is re-routed before it is lost, so no nodes are orphaned.
#include <cstddef>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* nxt = curr->next; // save successor before overwriting
curr->next = prev; // flip the pointer backward
prev = curr; // advance prev
curr = nxt; // advance curr
}
return prev; // prev is the new head once curr falls off the end
}
};
Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
// Taking 3 nodes to store the nodes.
ListNode* cur = head;
ListNode* prev = NULL;
ListNode* next = NULL;
// reversing the linked list
// 1->2->3->4->5 to 5->4->4->3->2->1
while(cur){
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) Time O(N) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.