Created
December 26, 2018 00:19
-
-
Save kanrourou/a1b282e8c58b2e20bc4589cf918fec76 to your computer and use it in GitHub Desktop.
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
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode(int x) : val(x), next(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
ListNode* insertionSortList(ListNode* head) { | |
if(!head || !head->next)return head; | |
ListNode* helper = new ListNode(-1); | |
helper->next = head; | |
auto curr = head; | |
while(curr->next) | |
{ | |
if(curr->next->val < curr->val) | |
{ | |
//find insert position | |
auto pre = helper; | |
while(pre->next->val < curr->next->val) | |
pre = pre->next; | |
//remove curr->next; | |
auto tmp = curr->next; | |
curr->next = curr->next->next; | |
//insert tmp | |
auto next = pre->next; | |
pre->next = tmp; | |
tmp->next = next; | |
} | |
else | |
curr = curr->next; | |
} | |
return helper->next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment