Skip to content

Commit d484763

Browse files
authored
Create MergeKSortedLists.java
1 parent 084a81a commit d484763

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

LeetCode/MergeKSortedLists.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//Solution to https://leetcode.com/problems/merge-k-sorted-lists/
2+
//Approach: We use the logic behind merging two sorted lists to merge k number of lists in sorted order.
3+
//Here two lists are taken at a time and merged. The process is repeated until the last one list in the array.
4+
5+
class Solution {
6+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
7+
ListNode h = new ListNode(0);
8+
ListNode ans=h;
9+
while (l1 != null && l2 != null) {
10+
if (l1.val < l2.val) {
11+
h.next = l1;
12+
h = h.next;
13+
l1 = l1.next;
14+
} else {
15+
h.next = l2;
16+
h = h.next;
17+
l2 = l2.next;
18+
}
19+
}
20+
if(l1==null){
21+
h.next=l2;
22+
}
23+
if(l2==null){
24+
h.next=l1;
25+
}
26+
return ans.next;
27+
}
28+
public ListNode mergeKLists(ListNode[] lists) {
29+
if(lists.length==0){
30+
return null;
31+
}
32+
int interval = 1;
33+
while(interval<lists.length){
34+
System.out.println(lists.length);
35+
for (int i = 0; i + interval< lists.length; i=i+interval*2) {
36+
lists[i]=mergeTwoLists(lists[i],lists[i+interval]);
37+
}
38+
interval*=2;
39+
}
40+
41+
return lists[0];
42+
}
43+
}

0 commit comments

Comments
 (0)