Flatten a Multilevel Doubly Linked List
这是我第一次参加 LeetCode (力扣) 的每月挑战题组,希望留下点笔记,大家可以参考和互相讨论。😃
第十天问
这是一道需要了解基本数据结构的问题,不过不是太难理解。只要你懂了 链表 (Linked list) 的基础结构和操作方法,就能轻易KO这道问题。
跟之前一样,首先看看这问题到底在问什麽:
给你有一个双链表,其中每个节点都有记录相应的前节点和后节点,不过跟普通的双链表不同,每个节点都可以有一个子指针指向另一张双链表。而且,每张双链表都或许有节点指向另一张子双链表,以此构成一张多层双链表 (Multilevel Doubly Linked List)。
现在,请你写一个程序,把这张多层双链表展平成单层双链表,使得所有节点都在同一层内。
知识点: 链表(Linked list)其实和普通我们认知的列表 (或者数列)很类似,但链表中每个值都是放左不同的节点裏,然后这些节点会带有指针指向下一个对应节点(或其位置)。
题目例子 (引用自LeetCode)
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:
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:
解题思路
了解了这个多层双链表的数据结构后,其实要做的只是把节点按不同顺序重新排列,当中需要检查每一个节点 (假设所有节点数为n),所以就有以下的步骤:
- 先把所有带子节点 (child node) 的父节点的下一节点就先记录好 (例如放在数列中)
- 把子节点换成其父节点的下一节点成为另一链表 (下称「总表」) ,再删除该父节点的子节点
- 重複以上两个步骤,直到没有任何节点带子节点
- 从总表的最后节点开始,跟数列中的最后节点相连接,变成新总表
- 找出新总表的最后节点,再把数列的倒数第二节点相连接
- 重複以上两个步骤,直到没数列所有节点连接完毕,总表就是答案。
代码 (时间复杂度:O(n))
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
currentNode = head
tmp = []
while currentNode:
if currentNode.child:
tmp.append(currentNode.next)
currentNode.next = currentNode.child
currentNode.next.prev = currentNode
currentNode.child = None
if currentNode.next:
currentNode = currentNode.next
else:
break
for index in range(len(tmp) -1, -1, -1):
if tmp[index]:
currentNode.next = tmp[index]
currentNode.next.prev = currentNode
while currentNode:
if currentNode.next:
currentNode = currentNode.next
else:
break
return head