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 *insertionSortList(ListNode *head) { if(!head||!head->next) return head; ListNode *pNode=new ListNode(10000);// record the position of head pNode->next=head; ListNode *spNode=pNode; ListNode* bpNode=head; while(bpNode->next){ if(bpNode->next->valval){ ListNode*cpNode=bpNode->next; bpNode->next=bpNode->next->next; while(spNode!=bpNode){ if(spNode->next->val>cpNode->val){ cpNode->next=spNode->next; spNode->next=cpNode; break; } else spNode=spNode->next; } spNode=pNode; } else bpNode=bpNode->next; } return pNode->next; } };