一个并不是十分标准的解法,供以后参考,由于head可能会变,使用一个dummy来记录头结点
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 *serchPostion(ListNode *head, int val){
ListNode *pNode = head;
while(pNode->next!=NULL && pNode->next->val<=val )
pNode=pNode->next;
return pNode;
}
ListNode *insertionSortList(ListNode *head) {
if(head==NULL||head->next==NULL) {
return head;
}
ListNode* dummy = new ListNode(-1);
dummy->next = NULL;
ListNode *new_next;
ListNode *pre,*next;
//ListNode iter = head;
while(head!=NULL) {
next = head->next;
pre = serchPostion(dummy,head->val);
new_next = pre->next;
head->next = new_next;
pre->next = head;
head = next;
}
return dummy->next;
}
};