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==NULL||head->next==NULL)
return head;
ListNode *p,*q,*r,*pre;
p=head;
q=p->next;
r=q;
p->next=NULL;
while(r!=NULL)
{
r=r->next;
if(head->val>q->val)
{
q->next=head;
head=q;
q=r;//r=r->next;
continue;
}
pre=p=head;
while(p!=NULL&&p->val<=q->val)
{
pre=p;
p=p->next;
}
if(p==NULL)
{
pre->next=q;
pre->next->next=NULL;
}
else{
pre->next=q;
pre->next->next=p;
}
q=r;
}
return head;
}
};