题目大意:有k个已经排序的链表,需要你将这k个链表合并成一个链表,并且保证有序。
解题思路:堆排序。
先申请一个k大小的小根堆,将每个链表的头一个节点放入堆进行排序。
每次取堆中最小的节点,链接到合并链表的尾部, 再将这个最小节点的后续节点放入小根堆中。
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct Comp {
bool operator()(const ListNode *n1, const ListNode *n2) {
return n1->val > n2->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.empty())
return NULL;
if(lists.size() == 1) {
return lists[0];
}
vector<ListNode *> heapNode;
for(vector<ListNode *>::iterator iter = lists.begin(); iter != lists.end(); iter++) {
if(*iter != NULL)
heapNode.push_back(*iter);
}
make_heap(heapNode.begin(), heapNode.end(), Comp());
ListNode *head = NULL;
ListNode *tail = NULL;
while(!heapNode.empty()) {
pop_heap(heapNode.begin(), heapNode.end(), Comp());
ListNode *cur = heapNode.back();
heapNode.pop_back();
if(head == NULL)
head = cur;
if(cur->next != NULL) {
heapNode.push_back(cur->next);
push_heap(heapNode.begin(), heapNode.end(), Comp());
}
if(tail != NULL) {
tail->next = cur;
}
tail = cur;
}
return head;
}
};
另一种方法是使用递归和归并排序。
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.empty())
return NULL;
if(lists.size() == 1) {
return lists[0];
}
split(lists, 0, lists.size() - 1);
}
private:
ListNode *split(vector<ListNode *> &lists, int start, int end) {
if(start <= end) {
if(start == end)
return lists[start];
int mid = (start + end) >> 1;
ListNode *l1 = split(lists, start, mid);
ListNode *l2 = split(lists, mid + 1, end);
return mergeTwoLists(l1, l2);
}
return NULL;
}
ListNode *mergeTwoLists(ListNode *A, ListNode *B) {
ListNode *head = NULL;
ListNode *tail = NULL;
ListNode *curA = A;
ListNode *curB = B;
if(A == NULL)
return B;
if(B == NULL)
return A;
while(curA != NULL && curB != NULL) {
if(curA->val <= curB->val) {
if(head == NULL)
head = curA;
else
tail->next = curA;
tail = curA;
curA = curA->next;
} else {
if(head == NULL)
head = curB;
else
tail->next = curB;
tail = curB;
curB = curB->next;
}
}
if(curA == NULL)
tail->next = curB;
if(curB == NULL)
tail->next = curA;
return head;
}
};