//10.1顺序表基本运算
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
typedef struct
{
int data[MAXSIZE]; //存储顺序表中的元素
int len; //顺序表的表长
}SeqList; //顺序表类型
SeqList* Init_SeqList() //顺序表初始化
{
SeqList *L;
L = (SeqList*)malloc(sizeof(SeqList));
L->len = 0;
return L;
}
void CreatList(SeqList **L) //建立顺序表
{
int i, n;
printf("Input length of List:");
scanf("%d", &n);
printf("Input elements of List:\n");
for (i = 1; i <= n; i++)
{
scanf("%d", &(*L)->data[i]);
}
(*L)->len = n;
}
void Insert_SeqList(SeqList *L, int i, int x) //在顺序表中插入元素
{
int j;
if (L->len == MAXSIZE - 1) //表满
{
printf("The List is full!\n");
}
else
{
if (i < 1 || i > (L->len + 1)) //插入位置非法
{
printf("The position is invalid!\n");
}
else
{
for (j = L->len; j >= i; j--) //将an--ai顺序后移一个元素位置
{
L->data[j+1] = L->data[j];
}
L->data[i] = x; //插入x到第i个位置
L->len++; //表长增1
}
}
}
void Delete_SeqList(SeqList *L, int i) //在顺序表中删除元素
{
int j;
if (L->len == 0) //表为空
{
printf("The List is empty!\n");
}
else
{
if (i < 1 || i > L->len) //删除位置非法
{
printf("The position is invalid!\n");
}
else
{
for (j = i + 1; j <= L->len; j++) //将ai+1 -- an 顺序前移一个位置实现对ai的删除
{
L->data[j-1] = L->data[j];
}
L->len--; //表长减1
}
}
}
int Location_SeqList(SeqList *L, int x) //在顺序表中查找元素
{
int i = 1; //从第一个元素开始查找
while (i < L->len && L->data[i] != x) //顺序表未查完且当前元素不是要找的元素
{
i++;
}
if (L->data[i] == x)
{
return i; //找到则返回其位置值
}
else
{
return 0; //未找到则返回0值
}
}
void print(SeqList *L) //顺序表的输出
{
int i;
for (i = 1; i <= L->len; i++)
{
printf("%4d", L->data[i]);
}
printf("\n");
}
void main()
{
SeqList *s;
int i, x;
s = Init_SeqList(); //顺序表初始化
printf("Create List:\n");
CreatList(&s); //建立顺序表
printf("Output list:\n");
print(s); //输出所建立的顺序表
printf("Input element and size of insert:\n");
scanf("%d%d", &x, &i); //输入要插入的元素x值和位置值i
Insert_SeqList(s, i, x); //将元素x插入到顺序表中
printf("Output list:\n");
print(s); //输出插入元素x后的顺序表
printf("Input element site of delete:\n");
scanf("%d", &i); //输入要删除元素的位置值i
Delete_SeqList(s, i); //删除顺序表第i个位置上的元素
printf("Output list:\n");
print(s); //输出删除元素后的顺序表
printf("Input element value of location:\n");
scanf("%d", &x); //输入要查找的元素x值
i = Location_SeqList(s, x); //定位要查找的元素x在顺序表中的位置
printf("element %d site is %d\n", x, i); //输出该位置的元素值
}
10.1顺序表基本运算
最新推荐文章于 2023-10-01 14:30:40 发布