Sort a linked list using insertion sort.
/**
* 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 *qpre = head;
ListNode *q = head->next;
while (q){
ListNode *p = head;
ListNode *ppre = NULL;
ListNode *cur = q;
while(p!=q && p->val < q->val){
ppre = p;
p = p->next;
}
if (p!=q){
cur = q->next;
qpre->next = q->next;
if(ppre){
q->next = ppre->next;
ppre->next = q;
}else{
q->next = p;
head = q;
}
q = cur;
}else{
qpre = q;
q = q->next;
}
}
return head;
}
};