顺序表的合并
/*顺序表的合并*/
#include<stdio.h>
#include<stdlib.h>
#define Max 20
/*用typedef声明新类型名sequencelist,代表一个结构体类型,可用新类型名去定义变量
* 命名一个新的类型名sequencelist来代表结构体类型*/
typedef struct {
int a[Max];//线性表占用的数组最大空间
int last;//记录线性表最后一个元素的位置
}sequencelist;
void print(sequencelist *Q){
int i;
for (i = 0; i <Q->last+1; i++)
{
printf("%3d", Q->a[i]);
}
printf("\n");
}
void mergelist(sequencelist*LA,sequencelist*LB,sequencelist*LC){
int i,j;
for(i=0;i<=LA->last;i++){
LC->a[i]=LA->a[i];
j=i;
LC->last++;
}
for(i=0;i<=LB->last;i++){
LC->a[j+1]=LB->a[i];
LC->last++;
j++;
}
}
int main(void){
int i;
sequencelist *LA;//定义指向结构体类型sequencelist的指针LA
sequencelist*LB;
sequencelist*LC;
LA = (sequencelist*)malloc(sizeof(sequencelist*)*20);//开辟sizeof(sequencelist*)*100字节的临时分配域,函数值为其第一个字节的地址,并赋值给指针变量LA
LA->last = -1;//空表表长置为-1
LB = (sequencelist*)malloc(sizeof(sequencelist*)*20);
LB->last = -1;
LC = (sequencelist*)malloc(sizeof(sequencelist*)*40);
LC->last = -1;
printf("connection LA and LB to LC:");
printf("\n");
printf("The list LA is:");
for (i = 0; i <10; i++)
{
LA->a[i] = i;
LA->last++;
printf("%2d", LA->a[i]);
}
printf("\nLA->last:%d\n",LA->last);
printf("The list LB is:");
fflush(stdout);
for (i = 0; i <10; i++)
{
scanf("%3d",&LB->a[i]);
LB->last++;
}
printf("LB->last:%d\n",LB->last);
mergelist(LA,LB,LC);
printf("The list LC is:\n");
print(LC);
printf("LC->last:%d\n",LC->last);
return 0;
}
调试结果
connection LA and LB to LC:
The list LA is: 0 1 2 3 4 5 6 7 8 9
LA->last:9
The list LB is:10 11 12 13 14 15 16 17 18 19
LB->last:9
The list LC is:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
LC->last:19