#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct LinearList { //定义线性表结构
int *list;
int size;
int MaxSize;
};
typedef struct LinearList LIST;
void InitList(LIST *L,int ms) { //初始化线性表
if((L->list=(int *)malloc(ms*sizeof(int)))==NULL) {
printf("内存申请错误!\n");
exit(1);
}
L->size=0;
L->MaxSize=ms;
}
int InsertList(LIST *L,int item, int rc) { //插入元素
int i;
if(L->size>=L->MaxSize) {
return -1;
}
if(rc<0) {
rc=0;
}
if(rc>=L->size) {
rc=L->size;
}
for(i=L->size-1; i>=rc; i--) {
L->list[i+1]=L->list[i];
}
L->list[rc]=item;
L->size++;
return 0;
}
void OutputList(LIST *L) { //输出
int i;
for(i=0; i<L->size; i++) {
printf("%d ",L->list[i]);
}
printf("\n");
}
int FindList(LIST *L,int item) { //查找元素
int i;
for(i=0; i<L->size; i++) {
if(L->list[i]==item) {
return i;
}
return -1;
}
}
int DeleteList1(LIST *L,int item) { //删除
int i,n;
for(i=0; i<L->size; i++) {
if(item==L->list[i]) {
break;
}
}
if(i < L->size) {
for(n=i; n<L->size-1; n++) {
L->list[n]=L->list[n+1];
}
L->size--;
return i;
}
return -1;
}
void main() {
LIST LL;
int i,r,flag;
printf("list addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MaxSize);
InitList(&LL,100);
printf("list addr=%p\tsize=%d\tMaxSize=%d\n",LL.list,LL.size,LL.MaxSize);
fflush(stdin);
while(1) {
printf("请输入你要执行的操作插入(1),查找(2),删除(3),退出(4):");
scanf("%d",&flag);
switch(flag) {
case 1:
while(1) {
printf("请输入元素值,输入0结束插入操作:");
fflush(stdin);
scanf("%d",&i);
if(i==0) {
break;
}
printf("请输入插入位置:");
scanf("%d",&r);
InsertList(&LL,i,r-1);
printf("线性表为:");
OutputList(&LL);
}
break;
case 2:
while(1) {
printf("请输入查找的元素,输入0结束查找操作:");
fflush(stdin);
scanf("%d",&i);
if(i==0) {
break;
}
r=FindList(&LL,i);
if(r<0) {
printf("没找到\n");
} else {
printf("有符合条件的元素,位置为:%d\n",r+1);
}
}
break;
case 3:
while(1) {
printf("亲输入删除元素值,输入0结束删除操作:");
fflush(stdin);
scanf("%d",&i);
if(i==0) {
break;
}
r=DeleteList1(&LL,i);
if(r<0) {
printf("没找到\n");
} else {
printf("有符合条件的元素,位置为:%d\n线性表为:");
OutputList(&LL);
}
}
break;
case 4:
exit(1);
break;
default :
printf("输入错误,没有此选项!!");
}
}
}
线性表-顺序表的增`删`改`查
最新推荐文章于 2023-04-16 17:44:10 发布