补发一个。
//顺序表
#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;
}