题目

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:

  1. Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
  2. Output: [1,2,3,7,8,11,12,9,10,4,5,6]
  3. Explanation:
  4. The multilevel linked list in the input is as follows:
  5. After flattening the multilevel linked list it becomes:

Example 2:

  1. Input: head = [1,2,null,3]
  2. Output: [1,3,2]
  3. Explanation:
  4. The input multilevel linked list is as follows:
  5. 1---2---NULL
  6. |
  7. 3---NULL

Example 3:

  1. Input: head = []
  2. Output: []

How multilevel linked list is represented in test case:

We use the multilevel linked list from Example 1 above:

  1. 1---2---3---4---5---6--NULL
  2. |
  3. 7---8---9---10--NULL
  4. |
  5. 11--12--NULL

The serialization of each level is as follows:

  1. [1,2,3,4,5,6,null]
  2. [7,8,9,10,null]
  3. [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. [1,2,3,4,5,6,null]
  2. [null,null,7,8,9,10,null]
  3. [null,11,12,null]

Merging the serialization of each level and removing trailing nulls we obtain:

  1. [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,指向下一层的链表。要求将给定的多层链表压平成一个链表。

思路

DFS处理,从下往上合并每一层;也可以直接用迭代从上往下合并每一层。


代码实现

Java

递归

  1. class Solution {
  2. public Node flatten(Node head) {
  3. dfs(head);
  4. return head;
  5. }
  6. // dfs返回压平后的当前链表的尾结点
  7. private Node dfs(Node head) {
  8. Node p = head;
  9. Node last = null;
  10. while (p != null) {
  11. if (p.next == null) {
  12. last = p;
  13. }
  14. if (p.child != null) {
  15. Node childLast = dfs(p.child);
  16. Node next = p.next;
  17. p.next = p.child;
  18. p.child.prev = p;
  19. p.child = null;
  20. childLast.next = next;
  21. if (next != null) {
  22. next.prev = childLast;
  23. }
  24. p = childLast;
  25. } else {
  26. p = p.next;
  27. }
  28. }
  29. return last;
  30. }
  31. }

迭代

  1. class Solution {
  2. public Node flatten(Node head) {
  3. Node p = head;
  4. while (p != null) {
  5. Node next = p.next;
  6. if (p.child != null) {
  7. Node q = p.child;
  8. while (q.next != null) {
  9. q = q.next;
  10. }
  11. p.next = p.child;
  12. p.child.prev = p;
  13. p.child = null;
  14. q.next = next;
  15. if (next != null) {
  16. next.prev = q;
  17. }
  18. }
  19. p = p.next;
  20. }
  21. return head;
  22. }
  23. }