#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;
}
数据结构顺序表的基本操作,查询、插入、删除
最新推荐文章于 2024-08-28 20:07:23 发布