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;
    }
};
相关推荐
Dream it possible!13 分钟前
LeetCode 面试经典 150_回溯_组合(99_77_C++_中等)
c++·leetcode·面试·回溯
再睡一夏就好31 分钟前
深入解析Linux页表:从虚拟地址到物理内存的映射艺术
linux·运维·服务器·c语言·c++·页表·缺页异常
Starry_hello world1 小时前
C++ 线程 (3)
c++
雍凉明月夜1 小时前
c++ 精学笔记记录Ⅲ
c++·笔记·学习
鹿角片ljp1 小时前
力扣234.回文链表-反转后半链表
算法·leetcode·链表
oioihoii1 小时前
C++共享内存小白入门指南
java·c++·算法
布茹 ei ai2 小时前
QtWeatherApp - 简单天气预报软件(C++ Qt6)(附源码)
开发语言·c++·qt·开源·开源项目·天气预报
Bruce_kaizy2 小时前
c++图论————图的基本与遍历
c++·算法·图论
Zmm147258369_2 小时前
好用的PC耐力板机构
c++
Code Slacker2 小时前
LeetCode Hot100 —— 普通数组(面试纯背版)(五)
数据结构·c++·算法·leetcode·面试