码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Merge k Sorted Lists

时间:2015-01-12 23:57:44      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:

Merge k Sorted Lists

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

 
采用优先队列priority_queue
把ListNode放入优先队列中,弹出最小指后,如果该ListNode有下一个元素,则把下一个元素放入到队列中
 
 
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9  
10 struct cmp
11 {
12     bool operator()(ListNode *a,ListNode *b)
13     {
14         //升序,每次优先队列返回最小的
15         return a->val>b->val;
16     }
17 };
18  
19 class Solution {
20    
21    
22 public:
23     ListNode *mergeKLists(vector<ListNode *> &lists) {
24        
25         priority_queue<ListNode *,vector<ListNode*>,cmp> q;
26        
27         for(int i=0;i<lists.size();i++)
28         {
29             if(lists[i]!=NULL) q.push(lists[i]);
30         }
31        
32         ListNode *front=new ListNode(0);
33         ListNode *result;
34         result=front;
35        
36         while(!q.empty())
37         {
38             ListNode *tmp=q.top();
39             front->next=tmp;
40             if(tmp->next!=NULL) q.push(tmp->next);
41             q.pop();
42             front=tmp;
43         }
44        
45         front->next=NULL;
46        
47         ListNode *tmp=result;
48         result=result->next;
49         delete tmp;
50         return result;
51        
52     }
53 };

 

【leetcode】Merge k Sorted Lists

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4220092.html

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