Each subpattern solves a specific type of problem. Click on a card to view its template.
Template for: Reversal
Keep prev = nullptr, curr = head, and next = nullptr before the loop begins.
Store next = curr->next before overwriting the pointer — otherwise you lose the rest of the list.
Set curr->next = prev, then advance: prev = curr, curr = next. Repeat until curr is nullptr.
When the loop ends, prev points to the new head of the reversed list.
1// Iterative reversal — O(N) time, O(1) space2ListNode* reverseList(ListNode* head)3{4 ListNode* prev = nullptr;5 ListNode* curr = head;67 while (curr)8 {9 ListNode* next = curr->next; // save before overwriting1011 curr->next = prev; // flip pointer12 prev = curr; // advance prev13 curr = next; // advance curr14 }1516 return prev; // new head17}
Sharpen your skills with hand-picked problems.
LeetCode #206
LeetCode #92
LeetCode #25
LeetCode #24
LeetCode #141
LeetCode #142
LeetCode #876
LeetCode #143
LeetCode #234
LeetCode #19
LeetCode #21
LeetCode #82
LeetCode #86
LeetCode #23
LeetCode #148
LeetCode #147
LeetCode #328
LeetCode #61
LeetCode #138
LeetCode #237
LeetCode #160
LeetCode #287
LeetCode #146