用插入排序实现对链表的排序
代码:
/**
* 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 || head->next==NULL)
return head;
ListNode *dummy = new ListNode(0);
ListNode *pre = dummy;
ListNode *cur = head;
while(cur!=NULL){
ListNode *next = cur->next;//记录下一个
pre = dummy;//回归原位(从头开始找)
while(pre->next!=NULL && pre->next->val < cur->val){//直到找到cur的位置(cur<prenext的位置)
pre = pre->next;
}
//把cur插入pre和pre的next之间
cur->next = pre->next;
pre->next = cur;
//cur移到后一个
cur = next;
}
return dummy->next;
}
};