6.3—排序—Merge k Sorted Lists

描述
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]);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值