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) 显式空间。
相关推荐
漫随流水27 分钟前
leetcode算法(111.二叉树的最小深度)
数据结构·算法·leetcode·二叉树
POLITE38 小时前
Leetcode 23. 合并 K 个升序链表 (Day 12)
算法·leetcode·链表
kaikaile199512 小时前
基于拥挤距离的多目标粒子群优化算法(MO-PSO-CD)详解
数据结构·算法
不忘不弃12 小时前
求两组数的平均值
数据结构·算法
leaves falling12 小时前
迭代实现 斐波那契数列
数据结构·算法
DonnyCoy13 小时前
Android性能之数据结构
数据结构
天赐学c语言13 小时前
1.7 - 删除排序链表中的重要元素II && 哈希冲突常用解决冲突方法
数据结构·c++·链表·哈希算法·leecode
菜鸟233号14 小时前
力扣96 不同的二叉搜索树 java实现
java·数据结构·算法·leetcode
空空潍14 小时前
hot100-最小覆盖字串(day12)
数据结构·算法·leetcode
yyy(十一月限定版)15 小时前
算法——二分
数据结构·算法