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->val<bpNode->val){ 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; } };
leetcode_num179_Insertion Sort list
原文地址:http://blog.csdn.net/eliza1130/article/details/44814499