码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-07-16 17:45:41      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   java   color   

bubuko.com,布布扣
 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 }
View Code

 

(java) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.,布布扣,bubuko.com

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

标签:des   style   blog   http   java   color   

原文地址:http://www.cnblogs.com/hansongjiang/p/3847638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!