LCR 026. 重排链表

LCR 026. 重排链表


题目链接:LCR 026. 重排链表

注:该题与 143. 重排链表完全一样

代码如下:

cpp 复制代码
class Solution {
public:
    void reorderList(ListNode* head)
    {
        if(head==nullptr||head->next==nullptr||head->next->next==nullptr)
            return;

        ListNode* Head=new ListNode;
        Head->next=nullptr;
        ListNode* r=head;

        //找到中间节点
        ListNode* slow=head,*fast=head,*slow_pre=nullptr;

        while(fast)
        {
            slow_pre=slow;
            slow=slow->next;
            fast=fast->next;
            if(fast)
                fast=fast->next;
        }

        slow_pre->next=nullptr;//前后链表进行断开操作

        //后半段进行逆置操作
        ListNode* afterLinkHead=new ListNode;
        afterLinkHead->next=nullptr;

        while(slow)
        {
            ListNode* temp=slow;
            slow=slow->next;

            temp->next=afterLinkHead->next;
            afterLinkHead->next=temp;
        }

        fast=head;
        slow=afterLinkHead->next;

        int count=0;
        while(fast&&slow)//轮流进行重新插入
        {
            ListNode* temp=nullptr;
            if(count%2==0)
            {
                temp=fast;
                fast=fast->next;
            }else
            {
                temp=slow;
                slow=slow->next;
            }

            temp->next=nullptr;
            r->next=temp;
            r=temp;

            count++;
        }

        while(fast)//把剩余的节点进行插入
        {
            ListNode* temp=fast;
            fast=fast->next;
            temp->next=nullptr;
            r->next=temp;
            r=temp;
        }

        while(slow)//把剩余的节点进行插入
        {
            ListNode* temp=slow;
            slow=slow->next;
            temp->next=nullptr;
            r->next=temp;
            r=temp;
        }

        head=Head->next;
    }
};
相关推荐
一直在努力的小宁1 小时前
《代码随想录-精华内容提取》07 二叉树
数据结构·算法·链表·面试
江塘1 小时前
机器学习-决策树多种生成方法讲解及实战代码讲解(C++/Python实现)
c++·python·决策树·机器学习
初见无风1 小时前
4.4 Boost库工具类assign 的使用
开发语言·c++·boost
月夜的风吹雨1 小时前
【C++ STL容器适配器】:解密Stack、Queue与Priority Queue的设计智慧
开发语言·c++·stl·优先级队列··队列·适配器
二川bro1 小时前
第48节:WebAssembly加速与C++物理引擎编译
java·c++·wasm
2501_941111931 小时前
基于C++的区块链实现
开发语言·c++·算法
hetao17338371 小时前
2025-11-16~17 hetao1733837的刷题记录
c++·算法
_OP_CHEN1 小时前
算法基础篇:(九)贪心算法拓展之推公式:从排序规则到最优解的推导艺术
c++·算法·贪心算法·推公式·算法竞赛·acm/icpc
czxyvX2 小时前
010-C++之List
开发语言·c++·list
2501_941111843 小时前
分布式日志系统实现
开发语言·c++·算法