#include<stdio.h>
#define Maxsize 50
//静态顺序表
typedef int Elemtype;
//定义顺序表
typedef struct
{
Elemtype date[Maxsize];
int Lenth;
}SqList;
//插入函数
bool ListInsert(SqList& test, int i, int t)
{
//插入位置的合法性判断
if (i<1 || i>test.Lenth + 1)
{
return false;
}
//判断是否空间不足
if (test.Lenth == Maxsize)
{
return false;
}
//移动
for (int j = test.Lenth; j >= i; j--)
{
test.date[j] = test.date[j - 1];
}
//插入
test.date[i - 1] = t;
test.Lenth++;
return true;
}
//删除函数
bool DeleteList(SqList& test, int i, int& t)
{
if (test.Lenth == 0 || i<1 || i>test.Lenth)
{
return false;
}
t = test.date[i - 1];
for (int j = i; j < test.Lenth; j++)
{
test.date[j - 1] = test.date[j];
}
test.Lenth--;
return true;
}
//值查询函数
int LocateElem(SqList& test, int t)
{
for (int i = 0; i < test.Lenth; i++)
{
if (test.date[i] == t)
{
return i + 1;
}
}
return 0;
}
//输出函数
void PrintList(SqList& test)
{
for (int i = 0; i < test.Lenth; i++)
{
printf("%d ", test.date[i]);
}
printf("\n");
}
int main()
{
//实例化
SqList test;
bool key;
//初始化
test.date[0] = 1;
test.date[1] = 2;
test.date[2] = 3;
test.Lenth = 3;
PrintList(test);
//插入
key = ListInsert(test, 1, 50);
if (key)
{
printf("插入成功\n");
}
else
{
printf("插入失败\n");
}
PrintList(test);
//删除
int t = 0;
bool k = DeleteList(test, 1, t);
if (k)
{
printf("删除成功\n");
printf("删除的值为%d\n", t);
PrintList(test);
}
else
{
printf("删除失败\n");
}
//查询
int temp = LocateElem(test, 2);
if (temp)
{
printf("查询的数在第%d位\n", temp);
}
else
{
printf("未查询到该数据\n");
}
return 0;
}
(王道练习代码仓库)顺序表 ———— C语言
最新推荐文章于 2024-11-02 16:12:52 发布