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) {}
* };
*/
所以就是在考insertion sort,AC代码:
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode dummy(0);
ListNode* pre=&dummy;
ListNode* cur=head;
dummy.next=head;
while(cur){
if(cur->next&&cur->next->val<cur->val){
while(pre->next&&pre->next->val<cur->next->val){
pre=pre->next;
}
ListNode* tmp=pre->next;
pre->next=cur->next;
cur->next=cur->next->next;
pre->next->next=tmp;
pre=&dummy;
}
else{
cur=cur->next;
}
}
return dummy.next;
}
};
看了别人的解答。。。。。亲自写还是有点难的。。(我好菜啊QUQ