力扣难题:重排链表

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

复制代码
/**
 * 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;
        }
    }
};
相关推荐
Ivanqhz38 分钟前
php8 use-def链
算法·php
evans在进步1 小时前
LeetCode 189 轮转数组:三次反转原地解决,图解 Java 实现
java·算法·leetcode
歌_顿1 小时前
Drawing_To_Model
算法
龍德明宇1 小时前
AI不会疼-龍德明宇
人工智能·算法·大语言模型llm·负主体性·ai存在论
302wanger2 小时前
程序员写 SOP:把脑子里的流程固化下来
算法
科学实验家2 小时前
完全背包
算法
Smoothcloud润云2 小时前
GPU租赁数据安全怎么做?
人工智能·算法·ai·aigc·gpu算力·gpu
呜喵王阿尔萨斯2 小时前
extern “C“ in C++
c语言·c++·算法
乐观勇敢坚强的老彭3 小时前
C++信奥静态数组和动态数组
数据结构·c++·算法
月光船幽幽3 小时前
呼吸孔设计重塑系统稳定性
python·科技·算法