首页 > 代码库 > Merge k Sorted Lists
Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
解题思路:一般而言,合并两个有序链表较为简单,只需要两两逐个比较即可.而本题要求合并K个有序链表,事实上只需要对每个链表的头结点建堆.每次输出最小值.并插入其所在链表的下个结点并维护堆.可以利用STL中的优先队列来完成.
#include<iostream> #include<vector> #include<queue> #include<functional> using namespace std; //Definition for singly - linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; struct ListCompare :public binary_function<ListNode*, ListNode*, bool>{ bool operator()(const ListNode*& x, const ListNode*& y)const{ return x->val < y->val; } }; ListNode *mergeKLists(vector<ListNode *> &lists) { priority_queue<ListNode*, vector<ListNode*>, ListCompare> Q_queue; for_each(lists.begin(), lists.end(), [&Q_queue](ListNode* head){if(head!=NULL)Q_queue.push(head);}); //建堆 ListNode* ResultNode = new ListNode(0); ListNode* TmpNode = ResultNode; while (!Q_queue.empty()){ ListNode* TopListNode = Q_queue.top(); Q_queue.pop(); TmpNode->next = TopListNode; TmpNode = TmpNode->next; if (TopListNode->next != NULL) Q_queue.push(TopListNode->next); } return ResultNode->next; }
Merge k Sorted Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。