数据结构--------顺序表的合并

#include<iostream>
using namespace std;
#define MAXSIZE 100
typedef struct node
{
	int *elem;
	int length;
}List;


void creatList(List &L)
{
	L.elem=new int[MAXSIZE];
	L.length=0;
	return;
}


void inputList(List &L,int n)
{
	int i=0;
	for(i;i<n;i++)
	{
		cout<<"请输入第"<<i+1<<"个数据:";
		cin>>L.elem[i];
	}
	L.length=i;
	return;
}


void output(List &L)
{
	cout<<"顺序表为:";
	int i=0;
	for(i;i<L.length;i++)
	{
		cout<<L.elem[i]<<" "; 
	}
	cout<<endl;
	return;
}


void MergeList(List LA,List LB,List &LC)
{
	LC.length=LA.length+LB.length;    //新表LC长度为A,B两表长度之和 
	LC.elem=new int[LC.length];       //为合并后的新表LC 分配一个新的空间 
	int i=0,j=0,k=0;
	while(i<LA.length && j<LB.length)
	{
		if(LA.elem[i]<=LB.elem[j])
		{
		   LC.elem[k]=LA.elem[i];
		   i++;
		   k++;
	    }
		else 
		{
			LC.elem[k]=LB.elem[j];
			j++;
			k++;
		}
	}
	while(i<LA.length)
	{
		LC.elem[k]=LA.elem[i];
		i++;
		k++; 
	}
	while(j<LB.length)
	{
		LC.elem[k]=LB.elem[j];
		j++;
		k++;
	}
	return;
}


int main()
{
	List LA;
	List LB;
	List LC;
	int a;
	int b;
	cout<<"表 A 填充的数据个数为:";
	cin>>a;
	cin.get();
	cout<<"表 B 填充的数据个数为:";
	cin>>b;
	creatList(LA);
	creatList(LB);
	cout<<"表 A 的输入为:"<<endl;
	inputList(LA,a);
	cout<<"表 B 的输入为:"<<endl;
	inputList(LB,b);
	cout<<"表 A 的展示如下:"<<endl;
	output(LA);
	cout<<"表 B 的展示如下:"<<endl;
	output(LB);
	cout<<"对表A和表B进行合并."<<endl;
	MergeList(LA,LB,LC);
	cout<<"合并后的表展示如下:"<<endl;
	output(LC);
	return 0;
}

本代码采用的是C++进行编译,对有顺序的两个表进行合并。代码中LA,LB表需要进行自行输入,你可以根据已知有顺序数据进行顺序输入,顺序为由小到大,即得有顺序的表LA,LB,再进行合并得到LC。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜雨时’

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值