Insertion Sort List


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,*pre,*next;
ListNode *help = new ListNode(0);
cur=head;

while(cur!=NULL)
{
next=cur->next;
pre=help;
while(pre->next!=NULL && pre->next->val<cur->val)
{
pre=pre->next;
}
cur->next=pre->next;
pre->next=cur;

cur=next;
}
return help->next;
}
};