📅  最后修改于: 2023-12-03 14:54:26.687000             🧑  作者: Mango
多级链表是指每个节点可能存在指向子链表的指针,子链表也可能存在指向更深层次子链表的指针,因此需要扁平化多级链表将其变为单链表。
public class FlattenMultilevelList {
public Node flatten(Node head) {
if (head == null) return null;
Node dummy = new Node(0, null, head, null);
flattenDFS(dummy, head);
dummy.next.prev = null;
return dummy.next;
}
//深度优先遍历节点
private Node flattenDFS(Node prev, Node cur) {
if (cur == null) return prev;
cur.prev = prev;
prev.next = cur;
Node tempNext = cur.next;
Node tail = flattenDFS(cur, cur.child);
cur.child = null;
return flattenDFS(tail, tempNext);
}
}
class Node {
public int val;
public Node prev;
public Node next;
public Node child;
public Node() {}
public Node(int val,Node prev,Node next,Node child) {
this.val = val;
this.prev = prev;
this.next = next;
this.child = child;
}
};
Node a = new Node(1, null, null, null);
Node b = new Node(2, a, null, null);
Node c = new Node(3, b, null, null);
a.next = b;
b.next = c;
Node d = new Node(4, b, null, null);
b.child = new Node(5, null, d, null);
Node e = new Node(6, c, null, null);
c.child = new Node(7, null, null, new Node(8, null, null, null));
FlattenMultilevelList solution = new FlattenMultilevelList();
Node result = solution.flatten(a);
//预期单链表: 1 -> 2 -> 5 -> 4 -> 3 -> 7 -> 8 -> 6