线性表的顺序存储结构

必做题)设计并验证以下算法:设顺序表A和B中的数据元素为整数且单调递增有序,将这两张表合并成顺序表C。
(1) 顺序表C单调递减有序。
(2) 根据键盘输入数据建立顺序表A和B。
(3) 输出顺序表A、B和C。

#include"stdio.h"
#include"malloc.h"
#include"stdlib.h"
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW -1
#define OK 1
typedef int ElemType;
typedef int Status;
typedef struct
{
	ElemType *elem;
	int length;
	int listsize;
}SqStack;
Status InitList_Sq(SqStack *);
void Create_Sq(SqStack *);
void Print_Sq(SqStack);
void Merge_Sq(SqStack ,SqStack ,SqStack *);
int Check_Sq(SqStack);
int main()
{	int ans;
	SqStack la,lb,lc;
	InitList_Sq(&la);
	InitList_Sq(&lb);
	InitList_Sq(&lc);
	Create_Sq(&la);
	ans=Check_Sq(la);
	while(ans==1)
	{
		printf("非法输入,请重输\n");
		Create_Sq(&la);
		ans=Check_Sq(la);
	}
	Create_Sq(&lb);
	int ans1=Check_Sq(lb);
	while(ans1==1)
	{
		printf("非法输入,请重输\n");
		Create_Sq(&lb);
		ans1=Check_Sq(lb);
	}
	printf("表A:\n");
	Print_Sq(la);
	printf("表B:\n");
	Print_Sq(lb);
	Merge_Sq(la,lb,&lc);
	printf("表C:\n");
	Print_Sq(lc);
	return 0;
}
Status InitList_Sq(SqStack *L)
{
	L->elem=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
	if(!L->elem)exit(OVERFLOW);
	L->length=0;
	L->listsize=STACK_INIT_SIZE;
	return OK;
}
void Create_Sq(SqStack *L)
{
	int n;
	printf("输入该有序表元素的个数:");
	scanf("%d",&n);
	while(n<0)
	{
		printf("非法输入,请重输:");
		scanf("%d",&n);
	}
	L->length=n;
	printf("输入该表(单调递增):\n",n);
	for(int i=0;i<n;i++)
	{scanf("%d",&L->elem[i]);}
}
void Print_Sq(SqStack L)
{
	for(int i=0;i<L.length;i++)
	{
		if(!i)printf("%d ",L.elem[i]);
		else printf("%d ",L.elem[i]);
	}
	printf("\n");
}
void Merge_Sq(SqStack la,SqStack lb,SqStack *lc)
{
	InitList_Sq(lc);
	lc->length=la.length+lb.length;
	int i=la.length-1,j=lb.length-1,k=0;
	while(i>=0 && j>=0)
	{   
		 if(la.elem[i]>=lb.elem[j])
		{
			lc->elem[k++]=la.elem[i];
			i--;
		}
		else
		{
			lc->elem[k++]=lb.elem[j];
			j--;
		}
	}
	while(i>=0)
	{
		lc->elem[k++]=la.elem[i];
		i--;
	}
	while(j>=0)
	{
		lc->elem[k++]=lb.elem[j];
		j--;
	}
}
int Check_Sq(SqStack la)
{
	int flag=0;
	for(int i=1;i<la.length;i++)
	{
		if(la.elem[i]<la.elem[i-1])flag=1;
	}
	return flag;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值