Skip to content

Commit

Permalink
Merge pull request #99 from ritikpatel17/patch-3
Browse files Browse the repository at this point in the history
Merge k Sorted Lists
  • Loading branch information
avastino7 authored Nov 1, 2022
2 parents fe33211 + 086842d commit ddf8452
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions mergeKLists.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {

//ListNode a = new ListNode();
if(lists.length==0){
return null;
}

for(int k=1; k<lists.length; k++) {
lists[k]=mergeTwoLists(lists[k],lists[k-1]);


}
return lists[lists.length-1];
}

public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null){
return list2;
}
if(list2==null){
return list1;
}
if(list1.val<list2.val){
list1.next = mergeTwoLists(list1.next , list2);
return list1;
}
else{
list2.next = mergeTwoLists(list2.next , list1);
}
return list2;
}
}

0 comments on commit ddf8452

Please sign in to comment.