-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_k_sorted_lists_lc23.java
42 lines (42 loc) · 1.22 KB
/
merge_k_sorted_lists_lc23.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
/**
* 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 head = new ListNode();
ListNode ptr = head;
int nullCounter = lists.length;
while (true)
{
int minMarker = 0;
for(int i = 0; i< lists.length ; i++)
{
if (lists[i] == null){
nullCounter --;
if(lists[minMarker] == null)
{
minMarker += 1;
}
continue;
}
if(lists[minMarker].val >= lists[i].val && minMarker != i)
{
minMarker = i;
}
}
if (nullCounter == 0) break;
ptr.next = new ListNode(lists[minMarker].val);
ptr = ptr.next;
lists[minMarker] = lists[minMarker].next;
nullCounter = lists.length;
}
return head.next;
}
}