思路
使用一个小顶堆,堆内的元素为链表,并按照链表的第一个元素进行排序。
java中优先队列的排序:
以小顶堆为例
Queue<ListNode> q = new PriorityQueue<>(
(ListNode l1,ListNode l2)->{
//升序排列
return l1.val-l2.val;
}
);
每次取堆顶链表的第一个元素,取下之后放回去,直到所有链表全部取空
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
Queue<ListNode> q = new PriorityQueue<>(
(ListNode l1,ListNode l2)->{
//升序排列
return l1.val-l2.val;
}
);
for(int i = 0;i<lists.length;i++){
if(lists[i]!=null)
{
q.add(lists[i]);
}
}
ListNode dummyNode = new ListNode(-1);
ListNode tail = dummyNode;
while(q.isEmpty()==false){
ListNode cur = q.remove();
tail.next = cur;
tail = tail.next;
if(cur.next!=null){
q.add(cur.next);
}
}
return dummyNode.next;
}
}