Skip to content

Commit b1243f2

Browse files
authored
Create Flatten a Multilevel Doubly Linked List.py
1 parent 3050683 commit b1243f2

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
'''
2+
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.
3+
4+
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.
5+
6+
Example:
7+
8+
Input:
9+
1---2---3---4---5---6--NULL
10+
|
11+
7---8---9---10--NULL
12+
|
13+
11--12--NULL
14+
15+
Output:
16+
1-2-3-7-8-11-12-9-10-4-5-6-NULL
17+
Explanation for the above example:
18+
19+
Given the following multilevel doubly linked list:
20+
21+
22+
23+
We should return the following flattened doubly linked list:
24+
25+
26+
'''
27+
28+
"""
29+
# Definition for a Node.
30+
class Node(object):
31+
def __init__(self, val, prev, next, child):
32+
self.val = val
33+
self.prev = prev
34+
self.next = next
35+
self.child = child
36+
"""
37+
class Solution(object):
38+
def flatten(self, head):
39+
"""
40+
:type head: Node
41+
:rtype: Node
42+
"""
43+
if not head:
44+
return None
45+
stack = [head]
46+
dummy = Node(0, None, None, None)
47+
current = dummy
48+
while stack:
49+
top = stack.pop()
50+
current.next = top
51+
top.prev = current
52+
current = current.next
53+
if top.next:
54+
stack.append(top.next)
55+
top.next = None
56+
if top.child:
57+
stack.append(top.child)
58+
top.child = None
59+
60+
dummy.next.prev = None
61+
return dummy.next

0 commit comments

Comments
 (0)