合并两个已排序的线性表——顺序表

写一个算法合并两个已排序的线性表。(用两种方法:数组表示的线性表(顺序表)和指针表示的线性表(链表))

       要求:1、定义线性表节点的结构,并定义节点的型和位置的型。

             2、定义线性表的基本操作

          3、在12的基础上,完成本题。

         4、在main函数中进行测试:先构建两个有序的线性表,然后合并这两个线性表。

#include <stdio.h>
#define maxlength 100
typedef int elementtype;
typedef int position;
struct LIST
{
	elementtype element[maxlength];
	int last;
};

void Insert(elementtype x,position p,LIST &L)
{
	position q;
	if(L.last>=maxlength)
		printf("此表已满!\n");
	else if(p>=maxlength||p<1)
		printf("插入位置错误!\n");
	else
	{
		for(q=L.last;q>=p;q--)
			L.element[q+1]=L.element[q];
		L.element[p]=x;
		L.last=L.last+1;
	}
	return;
}

position Locate(elementtype x,LIST &L)
{
	position p;
	for(p=1;p<=L.last;p++)
		if(L.element[p]==x)
			return p;
	return L.last+1;
}

elementtype Retrieve(position p,LIST &L)
{
	if(p<=L.last)
		return L.element[p];
	else
		printf("该位置不存在!\n");
	return 0;
}

void Delete(elementtype x,position p,LIST &L)
{
	position q;
	if(p>L.last||p<1)
		printf("该位置不存在!\n");
	else
	{
		for(q=p;q<L.last;q++)
			L.element[q]=L.element[q+1];
		L.last=L.last-1;
	}
	return;
}

void print(LIST &L)
{
	position p;
	for(p=1;p<=L.last;p++)
		printf("%d ",L.element[p]);
	printf("\n");
	return;
}

void merge(LIST &L1,LIST &L2,LIST &L3)
{
	position p1=1,p2=1,p3=1;
	while(p1<=L1.last&&p2<=L2.last)
	{
		if(L1.element[p1]<L2.element[p2])
		{
			Insert(L1.element[p1],p3,L3);
			++p3;
			++p1;
		}
		
		if(L1.element[p1]>=L2.element[p2])
		{
			Insert(L2.element[p2],p3,L3);
			++p3;
			++p2;
		}
	}
	for(;p1<=L1.last;p1++)
		Insert(L1.element[p1],p3,L3);
	for(;p2<=L2.last;p2++)
		Insert(L2.element[p2],p3,L3);
	return;
}

int main()
{
	LIST L1,L2,L3;
	L1.last=0;
	L2.last=0;
	L3.last=0;
	Insert(1, 1, L1);
	Insert(3, 2, L1);
	Insert(5, 3, L1);
	Insert(7, 4, L1);
	
	Insert(2, 1, L2);
	Insert(4, 2, L2);
	Insert(6, 3, L2);
	Insert(8, 4, L2);
	
	merge(L1,L2,L3);
	print(L3);
	return 0;
}

  • 9
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值