0

I am trying to understand this piece of code which basically performs insertion sort on a linked list. I am lost in this step.

cur->next = prev->next;

What is the role of this step?

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode* dummy = new ListNode();
        ListNode* prev = dummy ;
        ListNode* cur = head ;
        ListNode* next;
        
        while(cur!=NULL){
            next = cur->next ;
            while(prev->next!=NULL && prev->next->val <cur->val){
                prev = prev->next;
            }
            cout<<"prev->next is "<<prev->next<<endl;
            if(prev->next){
                cout<<"val is "<<prev->next->val <<endl;
            }
            cur->next = prev->next;
            prev->next = cur;
            
            prev = dummy ;
            cur = next;
        }
        return dummy->next ;
    }
};
1
  • 1
    Try drawing it on a paper and it will become clear. Commented Jun 25, 2021 at 21:28

1 Answer 1

1

That and the following line work together to insert cur between prev and prev->next.

cur->next = prev->next;
prev->next = cur;

Before:

prev -------.
            V    
   dummy -> 4 -> 8 -> 10 

cur --------.
            V    
            6 -> 3 -> 16 -> ...
                 ^
next ------------'

After cur->next = prev->next:

prev -------.
            V    
   dummy -> 4 -> 8 -> 10
                 ^
cur --------.   /
            V  /  
            6-/  3 -> 16 -> ...
                 ^
next ------------'

After prev->next = cur and cur = next:

prev -------.
            V    
   dummy -> 4    8 -> 10 
            |    ^
            |   /
            V  /  
            6-/  3 -> 16 -> ...
                 ^
next, cur -------'

So the list is now 4 -> 6 -> 8. next existed to allow the next step to work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.