LeetCode 23 Merge k Sorted Lists(优先队列|链表归并)
2016-03-29 15:58
302 查看
题意:归并k个有序链表。
思路:用优先队列存储每个链表的第一个元素,每次将最大的结点放到当前链表的尾部。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct cmp {
bool operator () (const ListNode* A, const ListNode* B) const {
return A->val > B->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp> q;
ListNode *head = new ListNode(0);
ListNode *tail = head;
for (int i = 0; i < lists.size(); i++) {
if (lists[i] != NULL) {
q.push(lists[i]);
}
}
while (!q.empty()) {
tail->next = q.top();
q.pop();
tail = tail->next;
if (tail->next != NULL)
q.push(tail->next);
}
return head->next;
}
};
思路:用优先队列存储每个链表的第一个元素,每次将最大的结点放到当前链表的尾部。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct cmp {
bool operator () (const ListNode* A, const ListNode* B) const {
return A->val > B->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp> q;
ListNode *head = new ListNode(0);
ListNode *tail = head;
for (int i = 0; i < lists.size(); i++) {
if (lists[i] != NULL) {
q.push(lists[i]);
}
}
while (!q.empty()) {
tail->next = q.top();
q.pop();
tail = tail->next;
if (tail->next != NULL)
q.push(tail->next);
}
return head->next;
}
};
相关文章推荐
- [C/C++]反转链表
- C#实现基于链表的内存记事本实例
- C语言实现带头结点的链表的创建、查找、插入、删除操作
- C++实现简单的学生管理系统
- Linux内核链表实现过程
- C++链表倒序实现方法
- C#通过链表实现队列的方法
- C#实现的简单链表类实例
- 找出链表倒数第n个节点元素的二个方法
- Java数据结构之简单链表的定义与实现方法示例
- C语言单循环链表的表示与实现实例详解
- C++实现的链表类实例
- PHP小教程之实现链表
- PHP中模拟链表和链表的基本操作示例
- C语言双向链表的表示与实现实例详解
- js链表操作(实例讲解)
- 优先队列(priority_queue)的C语言实现代码
- C语言实现输出链表中倒数第k个节点
- C++语言实现线性表之链表实例
- STL list链表的用法详细解析