#include<stdio.h>
#define MaxSize 50 //定义线性表的最大长度
typedef struct{
double data[MaxSize]; //顺序表的元素
int length; //顺序表的当前长度
}SqList; //顺序表的类型定义
//顺序表的初始化
bool ListInit(SqList &L)
{
L.length = 0;
return true;
}
//顺序表的插入操作
bool ListInsert(SqList &L, int i, double e)
{
//本算法将元素e插入到L的第i个位置
if (i<1 || i>L.length + 1)
return false;
if (L.length>MaxSize)
return false;
for (int j = L.length; j >= i; j--)
{
L.data[j] = L.data[j-1];
}
L.data[i - 1] = e;
L.length++;
return true;
}
//顺序表的按值查找操作:返回所在位置
int LocateElem(SqList L, double e)
{
int i;
for (i = 0; i < L.length; i++)
{
if (L.data[i] == e)
return i + 1; //找到则返回找到的位置
}
return -1; //不存在就返回-1
}
SqList L; //定义一个顺序表变量
//主函数
int main(void)
{
bool success;
//初始化顺序表
success = ListInit(L);
if (success == true)
printf("顺序表初始化成功\n");
else
printf("顺序表初始化失败\n");
//顺序表的插入操作
success = ListInsert(L, 1, 3.1); //在第1个位置插入3.1
success = ListInsert(L, 2, 8.4); //在第2个位置插入8.4
success = ListInsert(L, 3, 10); //在第3个位置插入10
if (success == true)
printf("顺序表的插入成功\n");
else
printf("顺序表的插入失败\n");
//顺序表的按值查找操作
int locate;
locate = LocateElem(L, 8.4); //查找8.4在线性表中的位置
if (locate == -1)
printf("元素不存在\n");
else
printf("元素8.4在线性表中的位置为:%d\n",locate);
}