链表-143.重排链表-力扣(LeetCode)

一、题目解析

1、不能单纯改变节点内部的值,要改变节点的指针

2、节点个数为1,5\*10\^4

二、算法原理

解法:模拟

对于上面的重排,我们可以将其拆解为两个链表合并,后面一个链表需要逆置,而分割的位置正好处于原链表的中间节点,由此我们可以模拟这个过程来重拍链表

1、找到链表的中间节点

快慢指针法

2、把后面的部分逆置

三指针头插法
只需按顺序链接即可,newhead->next = slow,slow->next = tail,tail = slow

3、合并两个链表

以一个哨兵为头节点,依次尾插即可,最后delete哨兵位头节点即可

画图可以解决指针链接问题,链表问题建议多画图

三、代码示例

cpp 复制代码
class Solution {
public:
    void reorderList(ListNode* head)
    {
        ListNode* cur1 = head,*cur2 = head;
        //找中间
        while(cur2 && cur2->next)
        {
            cur1 = cur1->next;
            cur2 = cur2->next->next;
        }
        //逆序后面(头插三指针)
        ListNode* newhead2 = new ListNode();
        newhead2->next = cur1;
        ListNode* cnext = cur1->next;
        cur1->next = nullptr;
        while(cnext)
        {
            ListNode* nnext = cnext->next;
            newhead2->next = cnext;
            cnext->next = cur1;
            cur1 = cnext;
            cnext = nnext;
        }
        //合并
        ListNode* newhead1 = new ListNode();
        ListNode* tail = newhead1;
        while(cur1)
        {
            tail->next = head;
            tail = head;
            if(head->next == nullptr) break;
            head = head->next;
            tail->next = cur1;
            tail = cur1;
            cur1=cur1->next;
        }
        //释放哨兵位头节点
        delete newhead1;
        delete newhead2;
    }
};

看到最后,如果对您有所帮助,还请点赞、收藏和关注,我们下期再见!

相关推荐
m0_547486664 天前
《数据结构教程》全套 PPT课件2026
数据结构
旖旎夜光4 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
CoderYanger4 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂4 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_104 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
tryxr4 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_34 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z4 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.4 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好4 天前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法