原题链接:Insertion Sort List
题解:
/**
* 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) {
/*
Time Complexity:O(N)
Space Complexity:O(1)
*/
if(!head || !head->next)return head;
ListNode *start=head,*tmp=head,*after=NULL;
head=head->next;
start->next=NULL;
while(head){
after=head->next;
while(tmp->next){
if(tmp->val<head->val && tmp->next->val<head->val)tmp=tmp->next;
else break;
}
if(tmp->val>head->val){
head->next=tmp;
start=head;
}
else{
head->next=tmp->next;
tmp->next=head;
}
tmp=start;
head=after;
}
return start;
}
};