题目:合并k个排序链表
思路:优先队列。
优先队列允许我们对自定义数据类型排序。
声明优先队列时,传入Comparator。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
PriorityQueue<ListNode> queue = new PriorityQueue<>( new Comparator<ListNode>(){
public int compare(ListNode n1, ListNode n2) {
return n1.val - n2.val;
}
});
for (ListNode l : lists) {
while (l != null) {
queue.add(l);
l = l.next;
}
}
ListNode fake = new ListNode(0);
ListNode head = fake;
while (!queue.isEmpty()) {
head.next = queue.poll();
head = head.next;
}
head.next = null;
return fake.next;
}
}