-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProblem-4.java
87 lines (71 loc) · 1.95 KB
/
Problem-4.java
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* @author Akash Goyal
*/
/**
--------------------- Problem----------->> Flatten a Linked List
Problem Link :- https://practice.geeksforgeeks.org/problems/flattening-a-linked-list/1
*/
class GfG
{
Node flatten(Node root)
{
// Your code here
Node result=root;
Node node=root;
while(node.next!=null)
{
result=merge(result,node.next);
node=node.next;
}
return result;
}
Node merge(Node result, Node root)
{
Node node1=result;
Node node2=root;
Node fin=null;
Node res=fin;
while(node1!=null && node2!=null)
{
if(node1.data<=node2.data)
{
if(res==null)
{
fin=node1;
res=node1;
node1=node1.bottom;
}
else
{
fin.bottom=node1;
node1=node1.bottom;
fin=fin.bottom;
}
}
else
{
if(res==null)
{
fin=node2;
res=node2;
node2=node2.bottom;
}
else
{
fin.bottom=node2;
node2=node2.bottom;
fin=fin.bottom;
}
}
}
if(node1!=null)
{
fin.bottom=node1;
}
if(node2!=null)
{
fin.bottom=node2;
}
return res;
}
}