Sort a linked list using insertion sort.
插入排序:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。
实现代码:
class Solution { public: ListNode *insertionSortList(ListNode *head) { if(head==NULL || head->next==NULL) return head; ListNode *cur=head; ListNode *helper=new ListNode(0); ListNode *pre; while(cur) { ListNode *next=cur->next; pre=helper; while(pre->next!=NULL && pre->next->val<cur->val) { pre=pre->next; } cur->next=pre->next; pre->next=cur; cur=next; } return helper->next; } };
原文地址:http://blog.csdn.net/wolongdede/article/details/43738351