Skip to main content

430. Flatten a Multilevel Doubly Linked List

https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list

Python

def flatten(self, head: 'Node') -> 'Node':
cur, stack = head, []
while cur:
if cur.child:
if cur.next:
stack.append(cur.next)
cur.child.prev, cur.next, cur.child = cur, cur.child, None
elif not cur.next and stack:
cur.next, cur.next.prev = stack.pop(), cur
cur = cur.next
return head