-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlattenLinkedList.py
58 lines (48 loc) · 1.26 KB
/
FlattenLinkedList.py
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#User function Template for python3
#problem link: https://practice.geeksforgeeks.org/problems/flattening-a-linked-list/1#
def findMin(root,dn):
node=root
minm=root
p=None
prev=p
while(node):
if node.data<minm.data and node!=dn:
prev=p
minm=node
p=node
node=node.next
return prev,minm
def flatten(root):
if root==None: return None
node=head
dummy_node=Node(-1)
#Attach dumy node to end of flat list
while(node.next):
node=node.next
node.next=dummy_node
#start populating the flatten list in sroted order
node=root
ptr=dummy_node
while(node!=dummy_node):
#find min node
p,minm=findMin(node,dummy_node)
#detach minm from list
btm=minm.bottom
nxt=minm.next
minm.next=None
minm.bottom=None
#attach minm to prt:
ptr.bottom=minm
ptr=ptr.bottom
#put btm in minm pos
if p and btm:
p.next=btm
btm.next=nxt
if p and not btm:
p.next=nxt
if btm and not p:
btm.next=nxt
node=btm
if not p and not btm:
node=nxt
return dummy_node.bottom