forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedList.java
More file actions
40 lines (39 loc) · 1.09 KB
/
MergeKSortedList.java
File metadata and controls
40 lines (39 loc) · 1.09 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
// Start typing your Java solution below
// DO NOT write main() function
for(int i = lists.size() - 1; i >=0; --i)
if(lists.get(i) == null)
lists.remove(i);
ListNode head = null, cur = null;
while(lists.size() > 0){
ListNode min = new ListNode(Integer.MAX_VALUE);
for(ListNode node: lists)
if(min.val > node.val)
min = node;
if(head == null){
head = min;
cur = head;
}
else{
cur.next = min;
cur = cur.next;
}
lists.remove(min);
if(min.next != null)
lists.add(min.next);
}
return head;
}
}