You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. 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.
Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
Example 1:
Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] Output: [1,2,3,7,8,11,12,9,10,4,5,6] Explanation: The multilevel linked list in the input is as follows:
After flattening the multilevel linked list it becomes:
Example 2:
Input: head = [1,2,null,3] Output: [1,3,2] Explanation: The input multilevel linked list is as follows: 1---2---NULL | 3---NULL
Example 3:
Input: head = [] Output: []
How multilevel linked list is represented in test case:
We use the multilevel linked list from Example 1 above:
1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL
The serialization of each level is as follows:
[1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null]
To serialize all levels together we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
[1,2,3,4,5,6,null] [null,null,7,8,9,10,null] [null,11,12,null]
Merging the serialization of each level and removing trailing nulls we obtain:
[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Constraints:
- Number of Nodes will not exceed 1000.
1 <= Node.val <= 10^5
扁平化多级双向链表。
题目即是题意,请你将这个多维的链表转化成一个一维的链表。
思路还是像遍历一般链表一样去遍历,当遇到child node的时候,看一下当前节点是否有next node,若有,需要用stack存下来,然后将当前node的next指针指向child,也将child的prev指针指向cur,最后记得将当前节点的child指针置为null。这样起码可以把多维的链表先变成一维的。此时此刻应该是会遍历到链表的尾部了,此时看一下stack是否为空,如果不为空,开始往外弹出节点,接到cur后面,同时记得将cur后边这个节点的prev指针再指向cur,这样才叫双向链表。
时间O(n)
空间O(n) - stack
Java实现
1 /* 2 // Definition for a Node. 3 class Node { 4 public int val; 5 public Node prev; 6 public Node next; 7 public Node child; 8 }; 9 */ 10 11 class Solution { 12 public Node flatten(Node head) { 13 // corner case 14 if (head == null) { 15 return head; 16 } 17 Deque<Node> stack = new ArrayDeque<>(); 18 Node cur = head; 19 while (cur != null) { 20 if (cur.child != null) { 21 if (cur.next != null) { 22 stack.push(cur.next); 23 } 24 cur.next = cur.child; 25 if (cur.next != null) { 26 cur.next.prev = cur; 27 } 28 cur.child = null; 29 } else if (cur.next == null && !stack.isEmpty()) { 30 cur.next = stack.pop(); 31 if (cur.next != null) { 32 cur.next.prev = cur; 33 } 34 } 35 cur = cur.next; 36 } 37 return head; 38 } 39 }
相关题目
114. Flatten Binary Tree to Linked List
430. Flatten a Multilevel Doubly Linked List