Leetcode 206. Reverse Linked List
Given the head of a singly linked list, reverse the list, and return the reversed list.
nullptr
).To reverse the linked list iteratively:
prev
, curr
, and next
.next
pointer to point to the previous node (prev
).Here’s the implementation in 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) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
// Store the next node
ListNode* nextTemp = curr->next;
// Reverse the current node's pointer
curr->next = prev;
// Move pointers one step forward
prev = curr;
curr = nextTemp;
}
return prev;
}
};
The time complexity of this solution is O(n), where n
is the number of nodes in the linked list. We traverse each node exactly once.
The space complexity is O(1) since we are using a constant number of extra pointers.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?