【发布时间】:2021-10-27 23:04:41
【问题描述】:
给你一个双向链表,除了 next 和 previous 指针之外,它可能有一个子指针,它可能指向也可能不指向单独的双向链表。这些子列表可能有自己的一个或多个子列表,依此类推,以生成多级数据结构,如下例所示。
扁平化列表,使所有节点出现在一个单级双向链表中。您将获得列表第一级的头部。
class Solution {
/*Global variable pre to track the last node we visited */
Node pre = null;
public Node flatten(Node head) {
if (head == null) {
return null;
}
/*Connect last visted node with current node */
if (pre != null) {
pre.next = head;
head.prev = pre;
}
pre = head;
/*Store head.next in a next pointer in case recursive call to flatten head.child overrides head.next*/
Node next = head.next;
flatten(head.child);
head.child = null;
flatten(next);
return head;
}
}
对于这个问题,上面的 leetcode 解决方案有效。但我不明白这一点:
/*Store head.next in a next pointer in case recursive call to flatten head.child overrides head.next*/
Node next = head.next;
谁能解释这部分? head.child 是如何覆盖 head.next 的?
【问题讨论】:
标签: java data-structures linked-list