本文共 2144 字,大约阅读时间需要 7 分钟。
多级双向链表中,除了指向下一个节点和前一个节点指针之外,它还有一个子链表指针,可能指向单独的双向链表。这些子列表也可能会有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。
给你位于列表第一级的头节点,请你扁平化列表,使所有结点出现在单级双链表中。
示例 1:
输入: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]
解释:
输入的多级列表如下图所示:
扁平化后的链表如下图:
示例 2:
输入:head = [1,2,null,3]
输出:[1,3,2]
解释:
输入的多级列表如下图所示:
示例 3:
输入:head = []
输出:[]
如何表示测试用例中的多级链表?
以 示例 1 为例:
序列化其中的每一级之后:
为了将每一级都序列化到一起,我们需要每一级中添加值为 null 的元素,以表示没有节点连接到上一级的上级节点。
合并所有序列化结果,并去除末尾的 null 。
class Solution { private Node pre = null; public Node flatten(Node head) { preOrder(head); return head; } //先序遍历 public void preOrder(Node head) { //判断是否这条路到尽头了 if (head == null) { return; } //要记录下一个结点,否则待会找不到 Node next = head.next; //如果pre为空代表是头结点,就跳过 if (pre != null) { pre.next = head; head.prev = pre; } pre = head; preOrder(head.child); //将child置为null head.child = null; preOrder(next); }}
class Solution { private Node pre = null; public Node flatten(Node head) { //定义一个头指针指向head,这样最后直接返回head即可 Node p = head; while (p != null) { if (p.child != null) { //记录存在child的结点的next结点 Node next = p.next; Node child = p.child; //将child置为null p.child = null; //将结点和child进行连接 p.next = child; child.prev = p; //遍历到末尾与上一层拼接 while (child.next != null) { child = child.next; } //上一层不为空才进行拼接 if (next != null) { child.next = next; next.prev = child; } } p = p.next; } return head; }}
转载地址:http://snpyz.baihongyu.com/