力扣同类题:重排链表

很明显做过一次

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;
        }
    }
};

相关推荐

  1. 】143. 重排

    2024-03-10 18:52:02       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-10 18:52:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-10 18:52:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-10 18:52:02       87 阅读
  4. Python语言-面向对象

    2024-03-10 18:52:02       96 阅读

热门阅读

  1. uniapp ui库 px 转 rpx

    2024-03-10 18:52:02       43 阅读
  2. PostgreSQL常用命令汇总

    2024-03-10 18:52:02       40 阅读
  3. CSS实现块级元素水平垂直居中的3种常用方式

    2024-03-10 18:52:02       42 阅读
  4. 调用GPL 开源库的法律问题

    2024-03-10 18:52:02       39 阅读
  5. Python与FPGA——帧间差算法

    2024-03-10 18:52:02       42 阅读
  6. Ajax与jQuery

    2024-03-10 18:52:02       39 阅读
  7. 轮询--一起学习吧之架构

    2024-03-10 18:52:02       39 阅读
  8. [LeetCode][LCR184]设计自助结算系统——单调队列

    2024-03-10 18:52:02       41 阅读