This file contains 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; | |
} | |
}; |
No comments:
Post a Comment