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 cur=head->next;
head->next=NULL;
ListNode temp,p,q;
while
(cur)
{
temp=cur;
q=head;
while
(q!=NULL && q->val<t->val)
{
p=q;
q=q->next;
}
cur=cur->next;
if
(q==head)
head=t;
else
p->next=t;
t->next=q;
}
return
head;
}
};