您的位置:首页 > 编程语言 > C语言/C++

Leetcode OJ : Merge k Sorted Lists 归并排序+最小堆 mergesort heap C++ solution

2015-02-18 12:56 375 查看
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/

struct helper {
ListNode *head;
int len;
helper(ListNode *h, int l) : head ( h ), len ( l ) {}
};

class helpercmp {
public:
bool operator() (const helper &a, const helper &b) {
return a.len > b.len;
}
};

class Solution {
public:
priority_queue<helper, vector<helper>, helpercmp> heap;

inline int listSize(ListNode *head) {
int len = 0;
for ( ; head != nullptr; head = head->next, len++ );
return len;
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
if ( lists.empty() ) return nullptr;
if ( lists.size() == 1 ) return lists[0];
ListNode *head = nullptr, *left = nullptr,  *right = nullptr;
for ( auto list : lists ) {
heap.push( helper(list, listSize(list) )  );
}
while ( heap.size() != 1 ) {
left = heap.top().head;
heap.pop();
right = heap.top().head;
heap.pop();
head = mergeList( left, right );
heap.push( helper( head, listSize(head) ) );
}
return heap.top().head;
}
ListNode *mergeList(ListNode *a, ListNode *b) {
ListNode dummy(0);
ListNode *tail = &dummy;
while ( a != nullptr && b != nullptr ) {
if ( a-> val <= b->val ) {
tail->next = a;
a = a->next;
} else {
tail->next = b;
b = b->next;
}
tail = tail->next;
}
tail->next =  a == nullptr ? b : a;
return dummy.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: