描述
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
#include<iostream>
#include<vector>;
using namespace std;
struct node
{
int data;
node *next;
};
class mylist
{
public:
node *head;
public:
mylist()
{
head = new node();
head->next = NULL;
}
void CreateList(int a[], int n);
void Display();
friend void ShowList(node *head);
friend void MergeTwoSort(node *list1, node *list2);
friend void MergeKSort(vector<node*>&alllsits);
~mylist();
};
void mylist::CreateList(int a[], int n)
{
node *p = head;
for (int i = 0; i < n; i++)
{
node *q = new node();
q->data = a[i];
p->next = q;
p = q;
}
p->next = NULL;
}
void mylist::Display()
{
node *p = head->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void MergeTwoSort(node *list1, node *list2)
{
if (list1->next == NULL || list2->next == NULL)
return;
node *pre = list1;
node *p = list1->next;
node *q = list2->next;
list2->next = NULL;
while (p&&q)
{
if (p->data < q->data)
{
pre->next = p;
pre = p;
p = p->next;
}
else
{
pre->next = q;
pre = q;
q = q->next;
}
}
if (p)
pre->next = p;
if (q)
pre->next = q;
}
void MergeKSort(vector<node*> &alllists)
{
if (alllists.size() <= 0)
return;
for (int i = 1; i < alllists.size(); i++)
{
MergeTwoSort(alllists[0], alllists[i]);
}
}
mylist::~mylist()
{
node *p = head;
while (p)
{
head = p->next;
delete p;
p = head;
}
}
void ShowList(node *head)
{
if (head->next == NULL)
return;
node *p = head->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main()
{
const int n = 6;
const int m = 4;
const int k = 3;
const int h = 2;
int a[n] = { 3, 9, 15, 17, 21, 24 };
int b[m] = { 1, 4, 8, 9 };
int c[k] = { 0, 5, 70 };
int d[h] = { -1, 2 };
mylist list1, list2,list3,list4;
list1.CreateList(a, n);
list2.CreateList(b, m);
list3.CreateList(c, k);
list4.CreateList(d, h);
vector<node*> alllists;
alllists.push_back(list1.head);
alllists.push_back(list2.head);
alllists.push_back(list3.head);
alllists.push_back(list4.head);
//=======================
MergeKSort(alllists);
ShowList(alllists[0]);
}