试编写一个算法,将两个有序线性表合成一个有序线性表...最好是在c++上可以直接运行出来的

本文介绍了一种使用C语言实现的顺序表合并方法,包括增序和逆序两种方式。通过对两个已排序的顺序表进行合并操作,可以得到一个新的按指定顺序排列的顺序表。文章提供了完整的代码示例,并展示了在VC6.0环境下运行该程序的具体过程及其结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<stdlib.h>
#include搜索<conio.h>
typedef int ElemType;
#define INITSIZE 100

typedef struct
{
 ElemType *data;
 int length;
 int listsize;
}sqlist;

/*初始化*/
void initlist(sqlist *L,int n)
{
 int i;
 L->data =(ElemType *)malloc(sizeof(ElemType)*INITSIZE);
 L->length=0;
 for(i=1;i<=n;i++)
 {
 scanf("%d",&L->data[i-1]);
 L->length++;
 }
 L->listsize=INITSIZE;
}

/*插入元素*/
int insert(sqlist *L,int i,ElemType x)
{
 int j;
 if(i<1||i>L->length+1) return 0;
 if(L->length==L->listsize) //存储空间不够,增加一个
 {
  L->data=(ElemType *)realloc(L->data,(L->listsize+1)*sizeof(ElemType));
  L->listsize++; //重置存储空间长度
 }
 for(j=L->length;j>=i;j--) 
  L->data[j]=L->data[j-1]; //将序号为i的结点及之后的结点后移
 L->data[i-1]=x; //在序号为i处放入x
 L->length++;

return 1;
} 
/*归并 增序*/
void merge(sqlist A, sqlist B, sqlist *C)
{
 int m =0, n=0;
 while (m < A.length && n<B.length)
  if(A.data[m]<B.data[n]) //将A的data[m]插入C尾部
  {
   insert(C,C->length+1,A.data[m]); 
   m++;
  }
  else //将B的data[n]插入C尾部
  {
   insert(C,C->length+1,B.data[n]); 
   n++;
  }

while(m<A.length) //B完,将A的剩余部分插入C
 {
  insert(C,C->length+1,A.data[m]); 
  m++;
 }
 while(n<B.length) //A完,将B的剩余部分插入C
 {
  insert(C,C->length+1,B.data[n]); 
  n++;
 }
}

/*归并 逆序*/
void merge1(sqlist A, sqlist B, sqlist *C)
{
 int m =0, n=0;
 while (m < A.length && n<B.length)
  if(A.data[m]<B.data[n]) //将A的data[m]插入C头部
  {
   insert(C,1,A.data[m]); 
   m++;
  }
  else //将B的data[n]插入C头部
  {
   insert(C,1,B.data[n]); 
   n++;
  }

while(m<A.length) //B完,将A的剩余部分插入C
 {
  insert(C,1,A.data[m]); 
  m++;
 }
 while(n<B.length) //A完,将B的剩余部分插入C
 {
  insert(C,1,B.data[n]); 
  n++;
 }
}

/*输出*/
void list(sqlist *L)
{
 int i;
 for(i=0;i<L->length;i++)
  printf("%d ",L->data[i]);
 printf("\n");
}

/*主函数*/
void main()
{
 int m=0,n=0;
 sqlist A,B,C;
 printf("please input the number of A elemtype M is:");
 scanf("%d",&m);
 initlist(&A,m);
 printf("please input the number of B elemtype N is:");
 scanf("%d",&n);
 initlist(&B,n);
 printf("merge A and B is C:\n");
 C.data =(ElemType *)malloc(sizeof(ElemType)*INITSIZE);
 C.length=0;
 C.listsize=INITSIZE;
 merge1(A,B,&C);
 list(&C);

}
 
以上是在VC6.0上运行通过的。 
//运行结果:
 
please input the number of A elemtype M is: 3
3 5 6
please input the number of B elemtype N is: 5
1 4 6 8 9

merge A and B is C:
9 8 6 6 5 4 3 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值