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) return NULL; ListNode *dumy = new ListNode(-1); dumy->next = head; ListNode *p = head->next; head->next = NULL; while(p) { ListNode *pNext = p->next; ListNode *q = dumy; while(q->next && q->next->val < p->val) q = q->next; p->next = q->next; q->next = p; p = pNext; } p = dumy->next; delete dumy; return p; } };