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;
    }
};
相关推荐
biter down16 分钟前
C++11 统一列表初始化+std::initializer_list
开发语言·c++
ShineWinsu1 小时前
爬虫对抗:ZLibrary反爬机制实战分析技术文章大纲
c++
charlie1145141912 小时前
通用GUI编程技术——Win32 原生编程实战(十六)——Visual Studio 资源编辑器使用指南
开发语言·c++·ide·学习·gui·visual studio·win32
AlenTech3 小时前
141. 环形链表 - 力扣(LeetCode)
数据结构·leetcode·链表
DpHard3 小时前
现代 C++ 中 push 接口为何提供 const T& 与 T&& 两个重载
c++
U-52184F694 小时前
深度解析:从 Qt 的 Q_D 宏说起,C++ 工业级 SDK 是如何保证 ABI 稳定性的
数据库·c++·qt
hz_zhangrl5 小时前
CCF-GESP 等级考试 2026年3月认证C++三级真题解析
c++·算法·程序设计·gesp·gesp2026年3月·gesp c++三级
kyle~5 小时前
C++----函数指针与函数指针类型 返回值类型 (*类型名)(参数列表)
开发语言·c++
努力中的编程者6 小时前
二叉树(C语言底层实现)
c语言·开发语言·数据结构·c++·算法
qq_416018726 小时前
高性能密码学库
开发语言·c++·算法