您的位置:首页 > 其它

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 优先队列