前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Insertion Sort List

Insertion Sort List

作者头像
用户1624346
发布2018-04-17 16:33:33
5520
发布2018-04-17 16:33:33
举报
文章被收录于专栏:calmoundcalmound

家里网实在太烂了,弄得我都不想上网,每次打开oj特别慢,提交题目等刷出来更慢。对于这题感觉脑子不好用啊,写的好繁琐。不过所幸最终脑子还是转过乐弯。。。就是指针next的交换,对于当前遍历的ret点,判断前面是否可以插入,若可以插入,则插入点的前一点指向ret,ret指向插入点的后一点, 然后再将前面已经排好序的链表的最后一个节点,指向ret的下一个节点。 注意要有个临时变量记录ret指针,在弄临时变量的next来遍历下一个要插入的节点,不然ret一旦插入后,其next就发生变化了。

代码语言:javascript
复制
class Solution
{
public:
    ListNode *insertionSortList(ListNode *head)
    {
        if(!head) return head;
        if(!head->next) return head;
        ListNode *sor,*ret;
        sor = new ListNode(-9999999);
        sor->next=head;
        ret=head->next;
        ListNode *pre1,*thi1;
        ListNode *pre2,*thi2;
        pre1=head;
        pre2=head;
        while(ret)
        {
            ListNode *tmp=ret;
            thi2=ret;
            pre1=sor;
            thi1=sor->next;
            while(thi1->val<ret->val && thi1!=ret)
            {
                thi1=thi1->next;
                pre1=pre1->next;
            }
            ret=thi2->next;
            if(thi1!=thi2)
            {
                pre2->next=thi2->next;
                pre1->next=thi2;
                thi2->next=thi1;
            }
            else pre2=tmp;
        }
        head=sor->next;
        delete sor;
        return head;
    }

} t;

方法二:参考的别人 建立一个helper头结点,然后依次将head链表中的结点有序的插入到helper链表中

代码语言:javascript
复制
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;
    }

} t;
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-07-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档