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 *findPre(ListNode *head, int val)
{
ListNode *pre;
ListNode *cur = head;
while(cur && cur->val <= val)
{
pre = cur;
cur = cur->next;
}
return pre;
}
ListNode *insertionSortList(ListNode *head)
{
if(!head || !head->next)
return head;
ListNode *newH = new ListNode(INT_MIN);
while(head)
{
ListNode *next = head->next;
ListNode *pre = findPre(newH, head->val);
head->next = pre->next;
pre->next = head;
head = next;
}
return newH->next;
}
};