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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head==NULL)return NULL; if(head->next==NULL)return head; ListNode* ret=head; ListNode* ptr,*tmp; head=head->next; ret->next=NULL;//Don't forget this one! while(head!=NULL){ if(head->val<ret->val){ ptr=head->next; head->next=ret; ret=head; head=ptr; } else{ ptr=ret; while(ptr->next!=NULL&&ptr->next->val<head->val){ ptr=ptr->next; } tmp=head->next; head->next=ptr->next; ptr->next=head; head=tmp; } } return ret; } };