力扣难题:重排链表

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

复制代码
/**
 * 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 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy2 小时前
力扣61.旋转链表
算法·leetcode·链表
卡卡卡卡罗特4 小时前
每日mysql
数据结构·算法
chao_7895 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
lifallen5 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest5 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
EndingCoder5 小时前
搜索算法在前端的实践
前端·算法·性能优化·状态模式·搜索算法
丶小鱼丶5 小时前
链表算法之【合并两个有序链表】
java·算法·链表
不吃洋葱.6 小时前
前缀和|差分
数据结构·算法
是白可可呀8 小时前
LeetCode 169. 多数元素
leetcode