力扣:430. 扁平化多级双向链表(官方)

This commit is contained in:
huangge1199 2021-02-19 10:13:08 +08:00
parent 50ede1f5ac
commit 33e2f1aa4c

View File

@ -0,0 +1,50 @@
package com.code.leet.Official.t20210219;
import com.code.leet.entiy.Node;
/**
* 多级双向链表中除了指向下一个节点和前一个节点指针之外它还有一个子链表指针可能指向单独的双向链表这些子列表也可能会有一个或多个自己的子项依此类推生成多级数据结构如下面的示例所示
* <p>
* 给你位于列表第一级的头节点请你扁平化列表使所有结点出现在单级双链表中
* <p>
*  
* <p>
* 示例 1
* <p>
* 输入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]
* <p>
* 来源力扣LeetCode
* 链接https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list
* 著作权归领扣网络所有商业转载请联系官方授权非商业转载请注明出处
*/
public class Flatten {
/**
* 430. 扁平化多级双向链表
*/
public Node flatten(Node head) {
if (head == null) return head;
// pseudo head to ensure the `prev` pointer is never none
Node pseudoHead = new Node(0, null, head, null);
flattenDFS(pseudoHead, head);
// detach the pseudo head from the real head
pseudoHead.next.prev = null;
return pseudoHead.next;
}
/* return the tail of the flatten list */
public Node flattenDFS(Node prev, Node curr) {
if (curr == null) return prev;
curr.prev = prev;
prev.next = curr;
// the curr.next would be tempered in the recursive function
Node tempNext = curr.next;
Node tail = flattenDFS(curr, curr.child);
curr.child = null;
return flattenDFS(tail, tempNext);
}
}