Skip to content

Commit c1d367d

Browse files
committed
Merge K Sorted LinkedLists
1 parent d174070 commit c1d367d

File tree

1 file changed

+130
-0
lines changed

1 file changed

+130
-0
lines changed

Programs/MergeKsortedLists.java

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
//Contributed by Dev jr - https://github.com/Dev-jr-8
2+
3+
class Solution
4+
{
5+
//Function to merge K sorted linked list.
6+
//Logic for merging two sorted linked list
7+
Node mergetwolist(Node head1, Node head2)
8+
{
9+
Node a = head1;
10+
Node b = head2;
11+
Node head = null;
12+
Node tail = null;
13+
14+
if(a==null)return b;
15+
if(b==null)return a;
16+
17+
if(a.data<b.data)
18+
{
19+
head = a;
20+
tail = a;
21+
a = a.next;
22+
}
23+
else
24+
{
25+
head = b;
26+
tail = b;
27+
b = b.next;
28+
}
29+
30+
while(a!=null && b!=null)
31+
{
32+
if(a.data<b.data)
33+
{
34+
tail.next = a;
35+
tail = a;
36+
a = a.next;
37+
}
38+
else
39+
{
40+
tail.next = b;
41+
tail = b;
42+
b = b.next;
43+
}
44+
}
45+
if(a==null)tail.next=b;
46+
if(b==null)tail.next=a;
47+
48+
return head;
49+
}
50+
51+
Node mergeKList(Node[]arr,int K)
52+
{
53+
//Add your code here.
54+
Node ans = null;
55+
//Taking pair of sorted linked list and merging them, Storing their start point(head)
56+
//in ans reference variable
57+
for(Node i : arr)
58+
{
59+
ans = mergetwolist(i,ans);
60+
}
61+
return ans;
62+
}
63+
//Time Complexity : o(n^2)
64+
//Space Complexity : o(1)
65+
}
66+
67+
//geeksforgeeks driver code
68+
69+
//{ Driver Code Starts
70+
import java.util.*;
71+
72+
class Node
73+
{
74+
int data;
75+
Node next;
76+
77+
Node(int key)
78+
{
79+
data = key;
80+
next = null;
81+
}
82+
}
83+
84+
85+
class GfG
86+
{
87+
public static void printList(Node node)
88+
{
89+
while(node != null)
90+
{
91+
System.out.print(node.data + " ");
92+
node = node.next;
93+
}
94+
}
95+
96+
public static void main (String[] args) {
97+
Scanner sc = new Scanner(System.in);
98+
99+
int t = sc.nextInt();
100+
while(t-- > 0)
101+
{
102+
int N = sc.nextInt();
103+
104+
Node []a = new Node[N];
105+
106+
for(int i = 0; i < N; i++)
107+
{
108+
int n = sc.nextInt();
109+
110+
Node head = new Node(sc.nextInt());
111+
Node tail = head;
112+
113+
for(int j=0; j<n-1; j++)
114+
{
115+
tail.next = new Node(sc.nextInt());
116+
tail = tail.next;
117+
}
118+
119+
a[i] = head;
120+
}
121+
122+
Solution g = new Solution();
123+
124+
Node res = g.mergeKList(a,N);
125+
if(res!=null)
126+
printList(res);
127+
System.out.println();
128+
}
129+
}
130+
}

0 commit comments

Comments
 (0)