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) {
ListNode* res = new ListNode(-1);
ListNode* cur = res;
while(head){
ListNode* next = head->next;
cur = res;
while(cur->next && cur->next->val<head->val){
cur = cur->next;
}
head->next = cur->next;
cur->next = head;
head = next;
}
return res->next;
}
};