数据结构-线性表的顺序表示-C(创建,插入,删除,合并)

补发一个。

//顺序表
#include<stdio.h>
#include<stdlib.h>
int  Max=100;
int  add=10;
typedef struct {
	int *elem;
	int length;
	int size;
}Sqlist;

int Create_list(Sqlist &L) {
	L.elem = (int *)malloc(Max * sizeof(int));
	if (!L.elem) {
		printf("顺序表构建失败\n");
		return 0;
	}
	L.length = 0;
	L.size = 100;
	printf("输入数据,输入-1结束\n");
	int i = 0;
	int num=0;
	while (num!=-1 && L.length!=100) {
		scanf_s("%d", &num);
		if (num != -1) {
			L.elem[i] = num;
			i++;
			L.length++;
		}
	}
}
//插入
int Insert_list(Sqlist &L, int e) {
	int i;
	printf("请输入插入位置\n");
	scanf_s("%d", &i);
	if (i<1 || i>L.length+1) {
		printf("越界\n");
		return 0;
	}
	if (L.length >= L.size) {
		int *newbase;
		 newbase= (int *)realloc(L.elem,(L.length + add)*sizeof(int));
		 if (!newbase) {
			 printf("空间增加失败\n");
			 return 0;
		 }
		 L.elem = newbase;
		 L.size += add;
	}
	for (int j = L.length; j >= i; j--) {
		L.elem[j + 1] = L.elem[j];
	}
	L.elem[i] = e;
	L.length++;
}
//删除
int Delete_list(Sqlist &L, int e) {
	int i = -1;
	for (int j = 0; j < L.length; j++) {
		if (L.elem[j] == e) {
			i = j;
			break;
		}
	}
	if (i < 0) {
		printf("表中不存在此数据\n");
		return 0;
	}
	for (int m = i + 1; m <L.length; m++) {
		L.elem[m - 1] = L.elem[m];
	}
	L.length--;
}
void travel_list(Sqlist &L) {
	for (int i = 0; i < L.length; i++) {
		printf("%d", L.elem[i]);
		printf(" ");
	}
	printf("\n");
}
//合并
int MergeList(Sqlist La, Sqlist Lb, Sqlist &Lc) {
	Lc.elem = (int *)malloc((La.size + Lb.size) * sizeof(int));
	if (!Lc.elem) {
		printf("内存空间分配失败\n");
		return 0;
	}
	Lc.length = 0;
	Lc.size = La.size + Lb.size;
	int pa = 0, pb = 0,pc=0;
	while (pa < La.length && pb < Lb.length) {
		if (La.elem[pa] > Lb.elem[pb]) {
			Lc.elem[pc] = Lb.elem[pb];
			pc++;
			pb++;
			Lc.length++;
		}
		if (La.elem[pa] < Lb.elem[pb]) {
			Lc.elem[pc] = La.elem[pa];
			pc++;
			pa++;
			Lc.length++;
		}
		if (La.elem[pa] == La.elem[pb]) {
			Lc.elem[pc] = La.elem[pa];
			pa++;
			pb++;
			pc++;
			Lc.length++;
		}
	}
	if (pa >= La.length) {
		while (pb < Lb.length) {
			Lc.elem[pc] = Lb.elem[pb];
			pc++;
			pb++;
			Lc.length++;
		}
	}
	if(pb>=Lb.length) {
		while (pa < La.length) {
			Lc.elem[pc] = La.elem[pa];
			pa++;
			pc++;
			Lc.length++;
		}
	}
}
int main() {
	/*Sqlist L;
	Create_list(L);
	travel_list(L);
	Insert_list(L, 8);
	travel_list(L);
	Delete_list(L, 1);
	travel_list(L);*/
	Sqlist La;
	Sqlist Lb;
	Sqlist Lc;
	Create_list(La);
	Create_list(Lb);
	MergeList(La, Lb, Lc);
	travel_list(La);
	travel_list(Lb);
	travel_list(Lc);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值