线性表-顺序表的增`删`改`查

#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("输入错误,没有此选项!!");
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值