0430. 扁平化多级双向链表

文章目录

题目链接

https://leetcode.cn/problems/flatten-a-multilevel-doubly-linked-list/

题目描述

将多级双向链表扁平化:把每个节点的 child 子链表插入到该节点与其 next 之间,最终得到单层双向链表,所有 child 置为 null。

推荐写法(返回尾节点,整体 O(n))

java 复制代码
/*
// Definition for a Node.
class Node {
    public int val;
    public Node prev;
    public Node next;
    public Node child;
}
*/
class Solution {
    public Node flatten(Node head) {
        flattenTail(head);
        return head;
    }

    // 扁平化以 head 为首的链表,返回该段扁平化后的尾节点
    private Node flattenTail(Node head) {
        Node cur = head;
        Node last = head; // 记录当前已扁平段的尾

        while (cur != null) {
            Node next = cur.next;
            if (cur.child != null) {
                // 先把 child 段扁平化,得到其尾节点 childTail
                Node childHead = cur.child;
                Node childTail = flattenTail(childHead);

                // 将 child 段插入 cur 与 next 之间
                cur.next = childHead;
                childHead.prev = cur;
                cur.child = null;

                // 接回 next
                if (next != null) {
                    childTail.next = next;
                    next.prev = childTail;
                }

                // 更新 last,并从 childTail 继续
                last = childTail;
                cur = next;
            } else {
                last = cur;
                cur = next;
            }
        }
        return last;
    }
}

复杂度分析

  • 时间复杂度:O(n),每个节点仅被访问和重连常数次。
  • 空间复杂度:O(d),d 为最大嵌套深度(递归栈);可改迭代+显式栈降为 O(h) 显式空间。
相关推荐
m0_5474866614 小时前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr19 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_319 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.19 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.20 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣20 小时前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9921 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王1 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水1 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1011 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质