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;
    }
};
相关推荐
achene_ql4 小时前
select、poll、epoll 与 Reactor 模式
linux·服务器·网络·c++
SY师弟6 小时前
51单片机——计分器
c语言·c++·单片机·嵌入式硬件·51单片机·嵌入式
豪斯有话说7 小时前
C++_哈希表
数据结构·c++·散列表
real_metrix8 小时前
【学习笔记】erase 删除顺序迭代器后迭代器失效的解决方案
c++·迭代器·迭代器失效·erase
朝朝又沐沐8 小时前
基于算法竞赛的c++编程(18)string类细节问题
开发语言·c++·算法
a.3029 小时前
C++ 时间处理指南:深入剖析<ctime>库
数据结构·c++·算法
Dave_Young10 小时前
上位机开发过程中的设计模式体会(1):工厂方法模式、单例模式和生成器模式
c++·设计模式
old_power10 小时前
在 Windows 系统下配置 VSCode + CMake + Ninja 进行 C++ 或 Qt 开发
c++·windows·vscode·cmake·ninja
UP_Continue11 小时前
C++--string的模拟实现
java·开发语言·c++
CodeWithMe11 小时前
【C/C++】高效的位操作
c语言·c++