力扣难题:重排链表

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

复制代码
/**
 * 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;
        }
    }
};
相关推荐
DoraBigHead17 分钟前
小哆啦解题记——两数失踪事件
前端·算法·面试
不太可爱的大白17 分钟前
Mysql分片:一致性哈希算法
数据库·mysql·算法·哈希算法
Tiandaren4 小时前
Selenium 4 教程:自动化 WebDriver 管理与 Cookie 提取 || 用于解决chromedriver版本不匹配问题
selenium·测试工具·算法·自动化
岁忧5 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7895 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
秋说7 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy7 小时前
力扣61.旋转链表
算法·leetcode·链表
卡卡卡卡罗特9 小时前
每日mysql
数据结构·算法
chao_78910 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
lifallen11 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法