/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#define tr(c,it) for(decltype((c).begin()) (it) = (c).begin(); (it) != (c).end(); (it)++)
typedef ListNode ln;
struct compare{
bool operator() (ListNode *a, ListNode *b) const
{
return (a->val > b->val);
}
};
ListNode *mergeKLists(vector<ListNode *> &lists) {
int n = lists.size();
if(n<1)return NULL;
vector<ListNode *> Cur;
ListNode *head = NULL, *last = NULL;
priority_queue<ListNode *,vector<ListNode *>, compare > pq;
tr(lists,it)
{
int i = it - lists.begin();
Cur.push_back(*it);
if(*it)
pq.push(*it);
}
while(!pq.empty())
{
ln *min = pq.top();
pq.pop();
if(!head)
{
head = min;
last = min;
}
else
{
last->next = min;
last = min;
}
if(last->next)
pq.push(last->next);
}
return head;
}
Saturday, September 20, 2014
LeetCode: Merge k Sorted Lists
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment