https://leetcode.com/problems/merge-k-sorted-lists/
倒没有什么难的
就是归并排序的链表版
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <stack>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class MergeTwo {
public:
void add(ListNode* &ret, int v) {
ret = new ListNode(v);
}
void copyList(ListNode* &a, ListNode* b) {
bool ff = (a == NULL);
while(b) {
add(a==NULL?a:a->next, b->val);
b = b->next;
if(ff){
ff=false;
head = a;
} else
a = a->next;
}
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *ret = NULL;
if(l1 == NULL && l2 == NULL)return ret;
flag = true; head = NULL;
while(l1 && l2) {
//ret = new ListNode();
if(l1->val <= l2->val) {
add(ret==NULL?ret:ret->next, l1->val);
l1 = l1->next;
} else {
add(ret==NULL?ret:ret->next, l2->val);
l2 = l2->next;
}
if(head == NULL) {
head = ret;
}
else
ret = ret -> next;
}
if(l1) {
copyList(ret, l1);
}
if(l2) {
copyList(ret, l2);
}
return head;
}
ListNode * createFromVector(vector <int> ivec) {
ListNode* ret = NULL,*head=NULL;
for(int i=0;i<ivec.size(); i++) {
if(i == 0) {
add(ret, ivec[i]);
head = ret;
} else {
add(ret->next, ivec[i]);
ret = ret->next;
}
}
return head;
}
private:
bool flag;
ListNode* head;
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() <= 0) return NULL;
if(lists.size() == 1) return lists[0];
if(lists.size() == 2 ) return combineLists(lists[0], lists[1]);
vector <ListNode*> leftList(lists.begin(), lists.begin()+lists.size()/2);
vector <ListNode*> rightList(lists.begin()+lists.size()/2, lists.end());
return combineLists( mergeKLists(leftList), mergeKLists(rightList) );
}
ListNode* combineLists(ListNode *a, ListNode *b) {
MergeTwo m;
return m.mergeTwoLists(a, b);
}
};
int main() {
int nlist;
vector<ListNode*> lists;
while(cin >> nlist) {
lists.clear();
for(int ilist=0;ilist<nlist;ilist++) {
int len;
vector<int> inlist;
cin >> len;
//ListNode *head;
int num;
for(int i=0; i<len; i++) {
cin >> num;
inlist.push_back(num);
}
MergeTwo m;
lists.push_back(m.createFromVector(inlist));
}
Solution s;
ListNode *head = s.mergeKLists(lists);
while(head) {
cout << head->val << ", ";
head = head->next;
}
cout << endl;
}
return 0;
}