数据结构顺序表的基本操作,查询、插入、删除

#include<stdio.h>
#define MAX 100
#define type int
typedef struct
{
	type elem[MAX];
	int last;

}Seqlist;
void init(Seqlist *L)
{
	L->last = -1;
}
void input(Seqlist *L)
{
	printf("输入数据 -1结束\n");
	int n, i;
	i = 0;
	scanf_s("%d", &n);
	while(n != -1)
	{
		L->elem[i] = n;
		scanf_s("%d", &n);
		i++;
	}
	L->last = i - 1;
}
void output(Seqlist L)
{
	int i = 0;
	for(;i <= L.last; i++)
		printf("%d ", L.elem[i]);
	printf("\n");
}
int Locate(Seqlist L, type e)
{
	int i = 0;
	for(i = 0; i <= L.elem[i]; i++)
		if(L.elem[i] == e)
			break;
	if(i <= L.last)
		return i + 1;
	else return -1;

}
int inslist(Seqlist *L, int i, type e)
{
	if(i < 1 || i > L->last + 2)// i = 6
	{
		printf("插入位置不合法");
		return 0;
	}
	if(L->last >= MAX - 1)
	{
		printf("表已满,无法插入");
		return 0;
	}
	int j;
	for(j = L->last; j >= i - 1; j--)
		L->elem[j + 1] = L->elem[j];
	L->elem[i - 1] = e;
	L->last++;
	return 1;
}
//1 2 3 5 6
//1 2 3 4 5 6
//0 1 2 3 4
int dellist(Seqlist *L, int i, type *e)
{
	if(i < 1 || i > L->last + 1)
	{
		printf("删除位置不合法");
		return 0;
	}
	*e = L->elem[i - 1];
	int j;
	for(j = i - 1; j < L->last; j++)
		L->elem[j] = L->elem[j + 1];
	L->last--;
	return 1;
}


int main()
{
	Seqlist L;
	int i, j;
	init(&L);
	input(&L);
	output(L);
	type e, m, q;
	printf("要查找的数为:");
	scanf_s("%d", &e);
	if(Locate(L, e) > 0)
		printf("查找的数为第%d个\n", Locate(L, e));
	else printf("查无此数\n");
	printf("要插入第几个数之前:");
	scanf_s("%d", &i);
	printf("要插入的数据为:\n");
	scanf_s("%d", &m);
	if(inslist(&L, i, m))
	{
		printf("已插在第%d数之前\n", i);
		output(L);
	}
	else printf("未插入成功");
	printf("要删除第几个数:\n");
	scanf_s("%d", &j);
	if(dellist(&L, j, &q))
	{
		printf("已删除第%d个数 删除的数为 %d\n", j, q);
		output(L);
	}
	else printf("未删除成功");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值