【c语言】数据结构—动态储存顺序表的扩容、合并(源代码)

#include 
#include 
#include 
#include  
#define MAXSIZE 3

//结构体定义
typedef int elemtype;
typedef struct sqList{
	elemtype *data;
	int size;			//当前长度 
	int capacity; 			//当前容量 
}sqList; 

//初始化
void init_sqList(sqList *Psql)
{
	assert(Psql);			//当参数为0时报错并终止程序 
	Psql->data=(elemtype *)malloc(MAXSIZE*sizeof(elemtype));
	Psql->capacity=MAXSIZE;
	Psql->size=0;
}
//扩容
void expland_sqList(sqList *Psql,int n)
{
	assert(Psql);
	if(Psql->size=Psql->capacity)	//表满 
	{
		Psql->capacity*=n;	//扩容成n倍 
		elemtype *new_data=(elemtype*)malloc(Psql->capacity*sizeof(elemtype));	//不建议用realloc函数 
		memcpy(new_data,Psql->data,Psql->size*sizeof(elemtype));	//从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中
		free(Psql->data);
		Psql->data=new_data;
		printf("扩容成功\n");
	} 
}
//合并顺序表 
sqList union_sqList(sqList *La,sqList *Lb)	//结构体变量作函数返回值 
{
	assert(La);
	assert(Lb);
	sqList Lc;
	Lc.size=La->size+Lb->size;
	Lc.capacity=Lc.size;
	Lc.data=(elemtype *)malloc(Lc.capacity*sizeof(elemtype));
	memcpy(Lc.data,La->data,La->size*sizeof(elemtype));
	memcpy(Lc.data+La->size,Lb->data,Lb->size*sizeof(elemtype));
	return Lc;
}

//其他基本操作与静态顺序表无异,最后结束记得释放内存 
void insert_sqList(sqList *Psql,int i,elemtype e)
{
	int j;
	assert(Psql);
	if(i<1||i>Psql->size+1||Psql->size==Psql->capacity)	//判断i是否正确和表是否满了 
	{				
		printf("The position is wrong\n");
		return;
	}
	for(j=Psql->size-1;j>=i-1;j--)		//从最后开始往右挪 插入得先挪再赋值 
		Psql->data[j+1]=Psql->data[j];
	Psql->data[i-1]=e;
	Psql->size++;
	printf("插入成功\n");
}
void print_sqList(sqList *Psql)
{
	assert(Psql);
	int i;
	if(Psql->size==0)
	{
		printf("NULL\n"); 
		return;
	}
	for(i=0;isize;i++)
	{
		printf("%d ",Psql->data[i]);
	}
	printf("\n"); 
}

int main()
{
	sqList La,Lb,Lc;
	elemtype e;int i,t;
	while((i=getchar())!='#')	//输入#退出循环 
	{
		switch(i)
		{
		case '1':init_sqList(&La);init_sqList(&Lb);printf("初始化成功\n");break;	//初始化 

		case '2':print_sqList(&La);print_sqList(&Lb);break;		//打印 
		case '3':printf("输入插入的位置以及插入元素\n");		//赋值 
				 scanf("%d %d",&t,&e);
				 insert_sqList(&La,t,e);
				 insert_sqList(&Lb,t,e);
				 break;
		case '4':expland_sqList(&La,2);expland_sqList(&Lb,2);break;	//扩容 
		case '5':Lc=union_sqList(&La,&Lb);printf("合并成功\n");break; 	//合并 
		case '6':print_sqList(&Lc);break;	 	//打印合并后的表 
		}
	}
	free(La.data);free(Lb.data);free(Lc.data);
	return 0;
}

你可能感兴趣的:(C语言,数据结构)