leetcode 430. Flatten a Multilevel Doubly Linked List

题目链接:leetcode

思路:
链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""
# 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):
"""
:type head: Node
:rtype: Node
"""
stack,cur = [],head
while cur:
if cur.child:
if cur.next:
stack.append(cur.next)
cur.next,cur.child.prev,cur.child = cur.child,cur,None
if not cur.next and len(stack) >0:
tmp = stack.pop()
tmp.prev,cur.next = cur,tmp
cur = cur.next
return head