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;
    }
};
相关推荐
世转神风-6 分钟前
qt-windows用户点击.exe,报错:缺少libgcc_s_seh-1.dll
c++·qt
慕容青峰10 分钟前
【牛客周赛 107】E 题【小苯的刷怪笼】题解
c++·算法·sublime text
羑悻的小杀马特38 分钟前
C++多线程同步工具箱:call_once精准触发、lock_guard/unique_lock智能管理,打造无死锁程序!
c++·多线程·死锁·lock_guard·unique_lock·call_once
电子_咸鱼38 分钟前
【QT——信号和槽(1)】
linux·c语言·开发语言·数据库·c++·git·qt
想唱rap44 分钟前
Linux下进程的控制
linux·运维·服务器·c++·算法
Queenie_Charlie1 小时前
小明统计数组
数据结构·c++·set
郝学胜-神的一滴1 小时前
Separate Buffer、InterleavedBuffer 策略与 OpenGL VAO 深度解析
开发语言·c++·程序人生·算法·游戏程序·图形渲染
承渊政道3 小时前
C++学习之旅【C++类和对象(下)】
c++·学习·visual studio
枫叶丹43 小时前
【Qt开发】Qt窗口(九) -> QFontDialog 字体对话框
c语言·开发语言·数据库·c++·qt
旖旎夜光10 小时前
多态(11)(下)
c++·学习