Skip to content

Commit 19e3ff1

Browse files
committed
Add
1 parent 65eb72b commit 19e3ff1

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <queue>
4+
#include <algorithm>
5+
using namespace std;
6+
7+
/**
8+
* Definition for singly-linked list.
9+
*/
10+
struct ListNode
11+
{
12+
int val;
13+
ListNode *next;
14+
ListNode() : val(0), next(nullptr) {}
15+
ListNode(int x) : val(x), next(nullptr) {}
16+
ListNode(int x, ListNode *next) : val(x), next(next) {}
17+
};
18+
19+
class Solution {
20+
public:
21+
ListNode *mergeKLists(vector<ListNode *> &lists)
22+
{
23+
if (lists.size() == 0)
24+
return NULL;
25+
26+
ListNode *res;
27+
auto cmp = [](ListNode *n1, ListNode *n2)
28+
{
29+
return n1->val > n2->val;
30+
};
31+
32+
/* 使用node的val构造一个小顶堆 */
33+
priority_queue<ListNode *, vector<ListNode *>, decltype(cmp)> nodes(cmp);
34+
for (auto list : lists)
35+
{
36+
if (list != NULL)
37+
{
38+
nodes.push(list);
39+
}
40+
}
41+
42+
ListNode *fakeHead = new ListNode(-1); /* 创建虚拟头结点 */
43+
ListNode *cur = fakeHead;
44+
while (!nodes.empty())
45+
{
46+
cur->next = nodes.top(); /* 取出最小值对应的结点指针,挂接在游标指针上 */
47+
cur = cur->next;
48+
nodes.pop();
49+
50+
if (cur->next != NULL) /* 只要挂接点后面还有结点,则将其压入栈,继续从中拿出最大值,循环往复 */
51+
{
52+
nodes.push(cur->next);
53+
}
54+
}
55+
56+
return fakeHead->next;
57+
}
58+
};
59+
60+
// Test
61+
int main()
62+
{
63+
Solution sol;
64+
// l1 = {1,2,4}, l2 = {1,3,4}
65+
ListNode *l1 = new ListNode(1);
66+
l1 -> next = new ListNode(2);
67+
l1 -> next -> next = new ListNode(4);
68+
ListNode *l2 = new ListNode(1);
69+
l1 -> next = new ListNode(3);
70+
l1 -> next -> next = new ListNode(4);
71+
vector<ListNode*> vec;
72+
vec.push_back(l1);
73+
vec.push_back(l2);
74+
ListNode* res = sol.mergeKLists(vec);
75+
76+
ListNode *p = res;
77+
while (p != NULL)
78+
{
79+
cout << p->val << endl;
80+
p = p->next;
81+
}
82+
83+
return 0;
84+
}

0 commit comments

Comments
 (0)