力扣难题:重排链表

首先通过快慢指针找到中间节点,然后将中间节点之后和之前的部分分为两个链表,然后翻转后面的链表,注意方法,然后将两个链表交替链接。

复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head||!head->next)
            return;
        ListNode *fast=head,*low=head;
        ListNode *pre=nullptr,*cur=nullptr,*next=nullptr;
        while(fast->next!=nullptr){
            fast=fast->next;
            if(fast->next)
                fast=fast->next;//如果不是最后一个就走两步
            low=low->next;
        }
        //当快指针到头,慢指针位置就是链表中间位置,cur指向后半段第一个
        cur=low->next;
        //不断开前半段的指针,会报错内存异常
        low->next=nullptr;
        //翻转从cur到结尾的链表部分
        while(cur){
            next=cur->next;
            cur->next=pre;
            pre=cur;
            cur=next;
        }
        //此时pre指向后半段翻转过的链表头,head是前半段的链表头
        //将pre的链表插入到head的链表间隔中
        cur=head;
        while(cur&&pre){
            ListNode *temp=pre->next;//保存pre的下一个
            pre->next=cur->next;
            cur->next=pre;
            cur=pre->next;
            pre=temp;
        }
    }
};
相关推荐
莹莹学编程—成长记2 小时前
string的模拟实现
服务器·c++·算法
ShiinaMashirol6 小时前
代码随想录打卡|Day27(合并区间、单调递增的数字、监控二叉树)
java·算法
wuqingshun3141598 小时前
蓝桥杯 5. 交换瓶子
数据结构·c++·算法·职场和发展·蓝桥杯
Demons_kirit8 小时前
Leetcode 2845 题解
算法·leetcode·职场和发展
adam_life9 小时前
http://noi.openjudge.cn/——2.5基本算法之搜索——200:Solitaire
算法·宽搜·布局唯一码
我想进大厂9 小时前
图论---朴素Prim(稠密图)
数据结构·c++·算法·图论
我想进大厂9 小时前
图论---Bellman-Ford算法
数据结构·c++·算法·图论
AIGC大时代10 小时前
高效使用DeepSeek对“情境+ 对象 +问题“型课题进行开题!
数据库·人工智能·算法·aigc·智能写作·deepseek
lkbhua莱克瓦2410 小时前
用C语言实现——一个中缀表达式的计算器。支持用户输入和动画演示过程。
c语言·开发语言·数据结构·链表·学习方法·交友·计算器
CODE_RabbitV10 小时前
【深度强化学习 DRL 快速实践】近端策略优化 (PPO)
算法