(java) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

时间:2023-03-08 20:19:40
(java)    Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
 /**
* 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(List<ListNode> lists) {
ListNode head=new ListNode(-1);
ListNode tail=head;
if(lists.size()<=0) return null;
Comparator<ListNode> mycmp=new Comparator<ListNode>()
{
public int compare(ListNode l1,ListNode l2)
{
if(l1.val>l2.val) return 1;
else if(l1.val<l2.val)return -1;
return 0; } } ; PriorityQueue<ListNode> prq=new PriorityQueue<ListNode>(lists.size(),mycmp);
for(ListNode n:lists)
{
if(n!=null)
{
prq.add(n);
} }
while(prq.size()>0)
{
ListNode tem=prq.poll();
tail.next=tem;
tail=tail.next;
if(tem.next!=null)
{
prq.add(tem.next);
} } return head.next; }
}