forked from striver79/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flatteningOfLinkedListJava
42 lines (34 loc) · 1012 Bytes
/
flatteningOfLinkedListJava
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
class GfG
{
Node mergeTwoLists(Node a, Node b) {
Node temp = new Node(0);
Node res = temp;
while(a != null && b != null) {
if(a.data < b.data) {
temp.bottom = a;
temp = temp.bottom;
a = a.bottom;
}
else {
temp.bottom = b;
temp = temp.bottom;
b = b.bottom;
}
}
if(a != null) temp.bottom = a;
else temp.bottom = b;
return res.bottom;
}
Node flatten(Node root)
{
if (root == null || root.next == null)
return root;
// recur for list on right
root.next = flatten(root.next);
// now merge
root = mergeTwoLists(root, root.next);
// return the root
// it will be in turn merged with its left
return root;
}
}