-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMergeKSortedList.java
64 lines (52 loc) · 1.49 KB
/
MergeKSortedList.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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode head = null,temp = null;
if(lists.length == 0 || lists == null){
return head;
}
int flag = 0;
while(flag == 0){
int tempVal = 0;
flag = 1;
int min = Integer.MAX_VALUE;
for(int i=0;i<lists.length;i++){
ListNode h = lists[i];
if(h != null){
if(h.val < min){
flag = 0;
min = h.val;
tempVal = i;
}
}
}
ListNode ll = lists[tempVal];
if(head == null){
head = ll;
temp = head;
}
else{
temp.next = ll;
temp = temp.next;
}
// System.out.println(ll.val);
try{
lists[tempVal] = ll.next;
}catch(Exception e){
}
// if(ll.next == null){
// lists[tempVal] = null;
// }
// else
// lists[tempVal] = ll.next;
}
return head;
}
}