首页 > 代码库 > (java) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
(java) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * }10 * }11 */12 public class Solution {13 public ListNode mergeKLists(List<ListNode> lists) {14 ListNode head=new ListNode(-1);15 ListNode tail=head;16 if(lists.size()<=0) return null;17 Comparator<ListNode> mycmp=new Comparator<ListNode>()18 {19 public int compare(ListNode l1,ListNode l2)20 {21 if(l1.val>l2.val) return 1;22 else if(l1.val<l2.val)return -1;23 return 0;24 25 26 27 }28 29 } ;30 31 PriorityQueue<ListNode> prq=new PriorityQueue<ListNode>(lists.size(),mycmp);32 for(ListNode n:lists)33 {34 if(n!=null)35 {36 prq.add(n);37 }38 39 }40 while(prq.size()>0)41 {42 ListNode tem=prq.poll();43 tail.next=tem;44 tail=tail.next;45 if(tem.next!=null)46 {47 prq.add(tem.next);48 }49 50 51 }52 53 return head.next;54 55 56 57 58 59 }60 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。