02
Sublist reversal (Linked List — Reversal Sub-pattern)
Find the node before the range, reverse exactly the range, then stitch both ends back. Everything outside the range stays as it was.
Signals in the problem statement
- ›
"reverse the nodes from position
lefttoright" - ›
"replace the nodes from
atobwith another list" - ›
"reverse only the groups whose length is even"
What makes it different
Reverse Linked List II is the plain version: head insertion inside the range, with a dummy node before it. Merge In Between is the same walk, but the range is cut out and another list is spliced into its place, so the order of the four relinks matters. Reverse Nodes in Even Length Groups repeats the idea on groups of growing size, so first count each group's real length (the last group may be shorter than it should be), then reverse only the even ones.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Reverse Linked List IIWalkthroughMediumBasic Anchor·LeetCode #92
- 2Merge In Between Linked ListsWalkthroughMediumSlight Variation·LeetCode #1669
- 3Reverse Nodes in Even Length GroupsWalkthroughMediumTricky / Edge Case·LeetCode #2074
Template
sublist-template.cpp
// Sublist reversal: reverse nodes at positions left..right (1-based), keep the rest.
// Head insertion: walk to the node before the range, then pull the node after
// the pivot to the front of the range, one at a time.
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode dummy(0, head); // a fixed node before head, so left = 1 is no special case
ListNode* before = &dummy;
for (int i = 1; i < left; i++) before = before->next; // before = the node just before the range
ListNode* pivot = before->next; // the first node of the range; it stays put
for (int i = left; i < right; i++) { // right - left flips
ListNode* moved = pivot->next; // 1. the node that jumps to the front
pivot->next = moved->next; // 2. close the gap it leaves behind
moved->next = before->next; // 3. it points at the current front of the range
before->next = moved; // 4. it becomes the new front
}
return dummy.next; // the dummy's next is the new head
}Remember this · Linked List — Reversal
Trigger
Reverse whole / part / every k nodes, reorder, palindrome check, numbers stored as lists.
Think
Which piece do I reverse, and which nodes must I remember to reconnect afterwards?
Key question
Before reversing, who is the node just before the piece and who is just after?