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 *newh=new ListNode(0); ListNode *p=head; while(p) { ListNode *pretmp=newh; ListNode *pnext=p->next; ListNode *tmp=newh->next; if(!tmp) { newh->next=p; newh->next->next=NULL; p=pnext; continue; } while(tmp) { if(p->val<=tmp->val) { pretmp->next=p; p->next=tmp; break; } else { pretmp=tmp; tmp=tmp->next; } } if(!tmp) { pretmp->next=p; pretmp->next->next=NULL; } p=pnext; } return newh->next; } };