首页 > 其他 > 详细

Leetcode:Insertion Sort List

时间:2015-02-11 22:00:54      阅读:243      评论:0      收藏:0      [点我收藏+]

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;
    }
};


Leetcode:Insertion Sort List

原文:http://blog.csdn.net/wolongdede/article/details/43738351

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!