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;
    }
};
相关推荐
zyeyeye12 分钟前
自定义类型:结构体
c语言·开发语言·数据结构·c++·算法
俩娃妈教编程36 分钟前
2023 年 03 月 二级真题(1)--画三角形
c++·算法·双层循环
航哥的女人1 小时前
C++文件操作
开发语言·c++
L_Aria2 小时前
3824. 【NOIP2014模拟9.9】渴
c++·算法·图论
ShineWinsu2 小时前
对于模拟实现C++list类的详细解析—上
开发语言·数据结构·c++·算法·面试·stl·list
Mr YiRan2 小时前
C++语言类中各个重要函数原理
java·开发语言·c++
程序员酥皮蛋2 小时前
hot 100 第二十九题 29.删除链表的倒数第 N 个结点
数据结构·算法·leetcode·链表
stripe-python2 小时前
十二重铲雪法(下)
c++·算法
D_evil__3 小时前
【Effective Modern C++】第五章:右值引用、移动语义和完美转发:29. 认识移动操作的缺点
c++
化学在逃硬闯CS3 小时前
【Leetcode热题100】108.将有序数组转换为二叉搜索树
数据结构·c++·算法·leetcode