Well, life gets difficult pretty soon whenever the same operation on array is transferred to linked list.
First, a quick recap of insertion sort:
Start from the second element (simply a[1]
head -> next -> val
in array and the annoying in linked list), each time when we see a node val
with smaller than it previous node, we scan from the and find the position, which the current head
node should is in Serted. Since a node may is inserted before head
, we create a that new_head
points to head
. The insertion operation, however, is a little easier for linked list.
Now comes the code:
1 classSolution {2 Public:3listnode* Insertionsortlist (listnode*head) {4listnode* New_head =NewListNode (0);5New_head-Next =head;6listnode* pre =New_head;7listnode* cur =head;8 while(cur) {9 if(cur, next && cur, Next, Val < curval) {Ten while(Pre, next && pre, Next, Val < cur, nextval) OnePre = PreNext; A /*Insert cur, next after pre.*/ -listnode* temp = PreNext; -Pre, next = curNext; theCur next = cur, nextNext; -Pre-Next Next =temp; - /*Move pre back to New_head.*/ -Pre =New_head; + } - Elsecur = curNext; + } Alistnode* res = New_headNext; at DeleteNew_head; - returnRes; - } -};
[Leetcode] Insertion Sort List