题目要求:对整型链表数组(vector<list<int>> src)进行多路归并排序,得到一个有序链表(list<int> dest)。
代码实现:
#include<stdafx.h>
#include <list>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
list <int> merge(vector < list<int> > &src)
{
size_t list_num = src.size();
size_t total_elem = 0;
//对每个链表排序
for (size_t i = 0; i != list_num; i++) {
src[i].sort();
total_elem += src[i].size();
}
//堆的实现比较复杂,这里用最简单的方式,当链表的个数很大的时候,需要采用堆。
list <int> dest;
while (total_elem--) {
int min= 0x7fffffff;
int which= -1;
for (int i = 0; i != list_num; i++)
{
if (src[i].empty())
continue;
if (src[i].front() < min) {
min = src[i].front();
which = i;
}
}
if (min!= 0x7fffffff && which != -1) {
src[which].pop_front();
dest.push_back(min);
}
}
return dest;
}
int main()
{
int n;
vector < list<int> > src;
cout<<"输入链表个数"<<endl;
cin >> n; //链表个数
for (int i = 0; i != n; i++) {
int m;//第I个链表长度
cout<<"输出第"<<i<<"个链表元素的个数"<<endl;
cin >> m;
list <int> tmp;
//这里可以输入无序组数
for (int j = 0; j != m; j++) {
cout<<"输出第"<<i<<"个链表第"<<j<<"个元素个数"<<endl;
int x;
cin >> x;
tmp.push_back(x);
}
src.push_back(tmp);
}
//输出所有链表
for (int i = 0; i != n; i++) {
for (list <int>::iterator it = src[i].begin(); it != src[i].end(); it++)
cout << *it << " ";
cout << endl;
}
//
list <int> dest =merge(src);
for (list <int>::iterator it = dest.begin(); it != dest.end(); it++)
cout << *it << " ";
cout << endl;
getchar();
return 0;
}