Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created December 26, 2018 00:19
Show Gist options
  • Save kanrourou/a1b282e8c58b2e20bc4589cf918fec76 to your computer and use it in GitHub Desktop.
Save kanrourou/a1b282e8c58b2e20bc4589cf918fec76 to your computer and use it in GitHub Desktop.
/**
* 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