-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMergeKSortedLists
More file actions
43 lines (42 loc) · 1.03 KB
/
MergeKSortedLists
File metadata and controls
43 lines (42 loc) · 1.03 KB
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
class trees.Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0)
return null;
ListNode node=sort(lists,0,lists.length-1);
return node;
}
public ListNode sort(ListNode [] arr,int l,int r){
if(l==r)
return arr[l];
int mid=(l+r)/2;
ListNode a=sort(arr,l,mid);
ListNode b=sort(arr,mid+1,r);
return merge(a,b);
}
public ListNode merge(ListNode a,ListNode b){
ListNode head=new ListNode();
ListNode n=head;
while(a!=null && b!=null){
if(a.val<b.val){
n.next=a;
n=n.next;
a=a.next;
}else{
n.next=b;
n=n.next;
b=b.next;
}
}
while(a!=null){
n.next=a;
a=a.next;
n=n.next;
}
while(b!=null){
n.next=b;
b=b.next;
n=n.next;
}
return head.next;
}
}