leetcode430. Flatten a Multilevel Doubly Linked List

You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.

Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.

Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.

你会得到一个双链表,其中包含的节点有一个下一个指针、一个前一个指针和一个额外的 子指针 。这个子指针可能指向一个单独的双向链表,也包含这些特殊的节点。这些子列表可以有一个或多个自己的子列表,以此类推,以生成如下面的示例所示的 多层数据结构 。

给定链表的头节点 head ,将链表 扁平化 ,以便所有节点都出现在单层双链表中。让 curr 是一个带有子列表的节点。子列表中的节点应该出现在扁平化列表中的 curr 之后 和 curr.next 之前 。

返回 扁平列表的 head 。列表中的节点必须将其 所有 子指针设置为 null 。

输入:head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]

输出:[1,2,3,7,8,11,12,9,10,4,5,6]
解释:输入的多级列表如上图所示。

扁平化后的链表如下图:
遇到一个节点有 child 的

复制代码
优先把 child 挪到该节点的 next 上面
然后一口气找到这个 child 链的最末尾(不要管这条 child 链中间是否还有其他的节点存在 child 分支,先跳过,后面处理)
把该末尾节点跟前面开的口子接上

完成上面一轮, curr 指针向前挪动一步,继续处理以上三步,这样就能够把题目的意思给模拟出来,扁平化链表。

迭代法

python 复制代码
class Solution:
    def flatten(self, head: 'Node') -> 'Node':
        curr = head
        while curr:
            if curr.child:
                nex = curr.next
                child = curr.child

                # 遇到一个child,先在 curr 这里豁开一个口子,把child变成 next 的关系
                curr.next = child
                curr.child = None
                child.prev = curr

                # 找到当前这个child链的最末尾
                while child.next:
                    child = child.next
                # 把child的最末尾的节点,跟上面豁开的口子 nex 接上
                if nex:
                    nex.prev = child
                child.next = nex
            curr = curr.next
        return head
相关推荐
梁下轻语的秋缘1 小时前
每日c/c++题 备战蓝桥杯 ([洛谷 P1226] 快速幂求模题解)
c++·算法·蓝桥杯
CODE_RabbitV1 小时前
【深度强化学习 DRL 快速实践】逆向强化学习算法 (IRL)
算法
mit6.8242 小时前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
keep intensify2 小时前
通讯录完善版本(详细讲解+源码)
c语言·开发语言·数据结构·算法
shix .2 小时前
2025年PTA天梯赛正式赛 | 算法竞赛,题目详解
数据结构·算法
风铃儿~2 小时前
Java面试高频问题(26-28)
java·算法·面试
wuqingshun3141592 小时前
蓝桥杯 4. 卡片换位
算法·职场和发展·蓝桥杯
江沉晚呤时2 小时前
深入了解C# List集合及两种常见排序算法:插入排序与堆排序
windows·sql·算法·oracle·c#·排序算法·mybatis
Eric.Lee20213 小时前
数据集-目标检测系列- F35 战斗机 检测数据集 F35 plane >> DataBall
人工智能·算法·yolo·目标检测·计算机视觉
Gsen28193 小时前
AI大模型从0到1记录学习 数据结构和算法 day20
数据结构·学习·算法·生成对抗网络·目标跟踪·语言模型·知识图谱