AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 校园
  • 应用
  • 文章
    • 题解
    • 分享
    • 问答
  • 吐槽
  • 登录/注册

LeetCode 148. 排序链表    原题链接    中等

作者: 作者的头像   腾杨天下 ,  2022-01-15 20:16:51 ,  所有人可见 ,  阅读 55


1


思路

太他妈难了我草

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        int n=0;
        for(auto p=head;p;p=p->next)n++;
        auto dummy=new ListNode(-1);
        dummy->next=head;
        for(int i=1;i<n;i*=2)
        {
            auto cur=dummy;
            for(int j=1;j+i<=n;j+=i*2)
            {
                auto p=cur->next,q=p;
                for(int k=0;k<i;k++)q=q->next;
                int x=0,y=0;
                while(x<i&&y<i&&p&&q)
                {
                    if(p->val<=q->val)cur=cur->next=p,p=p->next,x++;
                    else cur=cur->next=q,q=q->next,y++;
                }
                while(x<i&&p)cur=cur->next=p,p=p->next,x++;
                while(y<i&&q)cur=cur->next=q,q=q->next,y++;
                cur->next=q;//将cur->next移向新的j循环开始节点,不然的话cur->next只可能指在p段或q段上,不可能指向q段的下一个节点。
            }
        }
        return dummy->next;
    }
};

0 评论

你确定删除吗?
1024
x

© 2018-2022 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息