思路:
/**
* 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 *dummy = new ListNode(-1);
dummy->next = head;
ListNode *pre = dummy, *cur = head;
while(cur != NULL) {
if(cur->next && cur->next->val < cur->val){
while(pre->next && pre->next->val < cur->next->val) {
pre = pre->next;
}
//将cur->next指向的node插到pre指向的node的后面
ListNode *tmp = pre->next;
pre->next = cur->next;
cur->next = cur->next->next;
pre->next->next = tmp;
//恢复pre到初始状态
pre = dummy;
}else {
cur = cur->next;
}
}
ListNode *ans = dummy->next;
delete dummy;
return ans;
}
};