必做题)设计并验证以下算法:设顺序表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;
}