Sort a linked list using insertion sort.
建立一个新头结点,然后依次将head链表中的结点有序的插入到新链表中
/**
/**
* 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* vhead=new ListNode(-1);
//vhead->next=head;
ListNode* cur=head;
ListNode* pre;
while(cur !=NULL){
pre=vhead;
ListNode* tmp=cur->next;
while(pre->next!=NULL && pre->next->val <= cur->val){
pre=pre->next;
}
cur->next=pre->next;
pre->next=cur;
cur=tmp;
}
head=vhead->next;
delete vhead;
return head;
}
};