Created
          July 11, 2020 08:50 
        
      - 
      
- 
        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
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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