-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedLists.cpp
More file actions
50 lines (43 loc) · 1.19 KB
/
MergeKSortedLists.cpp
File metadata and controls
50 lines (43 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/***
* 维护一个长度为k的小顶堆
* 每次从各个有序表中取一个放入堆中
* 然后从中取最小的加入到新的链表
* 小顶堆可以用priority_queue
***/
struct cmpnode {
bool operator() (ListNode *a, ListNode *b)
{
return (a->val > b->val);
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if (0 == lists.size())
return NULL;
priority_queue<ListNode *, vector<ListNode *>, cmpnode> pheap;
for (int i = 0; i < lists.size(); ++i)
if (NULL != lists[i])
pheap.push(lists[i]);
ListNode *mlist = new ListNode(-1); // null head
ListNode *mnode = mlist;
while (!pheap.empty())
{
ListNode *pnode = pheap.top(); // get the smallest node
pheap.pop();
mnode->next = pnode; // merge
mnode = pnode;
if (NULL != pnode->next)
pheap.push(pnode->next);
}
return mlist->next;
}
};