Skip to content

Instantly share code, notes, and snippets.

@JyotinderSingh
Created July 11, 2020 08:50
Show Gist options
  • Save JyotinderSingh/96fec7f9af3712c6cf765dedb7bf13b2 to your computer and use it in GitHub Desktop.
Save JyotinderSingh/96fec7f9af3712c6cf765dedb7bf13b2 to your computer and use it in GitHub Desktop.
Reverse Sublist in a Linked List (Reverse Linked List - II on LeetCode) | Algorithm Explanation
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int start, int end) {
if(!head || start == end) return head;
ListNode dummyHead(INT_MIN);
dummyHead.next = head;
auto* nodeBeforeReversedSublist = &dummyHead;
int pos = 1;
while(pos < start) {
nodeBeforeReversedSublist = nodeBeforeReversedSublist->next;
pos++;
}
auto* sublistWorkingPtr = nodeBeforeReversedSublist->next;
while(start < end) {
// cut the new node out
auto* nodeComingToSublistFront = sublistWorkingPtr->next;
sublistWorkingPtr->next = nodeComingToSublistFront->next;
// pasting it at the front
nodeComingToSublistFront->next = nodeBeforeReversedSublist->next;
nodeBeforeReversedSublist->next = nodeComingToSublistFront;
start++;
}
return dummyHead.next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment