#include<iostream>
using namespace std;
#define size 100
typedef struct list
{
int data[size];
int length;
}list;
//创建顺序表
void CreateList(list *L, int n)
{
int i;
for (i = 0; i < n; i++)
cin >> L->data[i];
L->length = n;
}
//求表长
int Length(list L)
{
return L.length;
}
//判断是否为空
bool IsEmpty(list L)
{
if (L.length == 0)
return 1;
else
return 0;
}
//判断是否为满
bool IsFull(list L)
{
if (L.length == size)
return 1;
else
return 0;
}
//清空表
void ClearList(list *L)
{
L->length = 0;
}
//输出表元素
void ShowList(list L)
{
if (IsEmpty(L) || L.length > size)
cout << "超出范围" << endl;
for (int i = 0; i < L.length; i++)
cout << L.data[i] << ' ';
cout << endl;
}
//按位置查找元素
int SearchList(list L, int k)
{
int i = 0;
while (i < k - 1)
++i;
return L.data[i];
}
//按值查找
int VSearchList(list L, int e)
{
for (int j = 0; j < L.length; ++j)
{
if (L.data[j] == e)
return ++j;
}
}
//寻找元素前驱
int FirstSearchList(list L, int e)
{
int i = 0;
while (L.data[i] != e && i<L.length )
i++;
if (i == 0)
{
cout << "无前驱" << endl;
return -1;
}
else if (i <= L.length - 1)
{
return L.data[i-1];
return -1;
}
else
{
cout << "无该元素";
return -1;
}
}
//寻找元素后继
int NextSearchList(list L, int e)
{
int i = 0;
while (L.data[i] != e && i < L.length)
i++;
if (i == L.length - 1)
{
cout << "无后继" << endl;
return -1;
}
else if (i <= L.length - 1)
{
return L.data[i + 1];
return -1;
}
else
{
cout << "无该元素";
return -1;
}
}
//插入元素
list InsertList(list L, int i, int e)
{
int j;
if (L.length != size)
{
if (i == L.length)
L.data[i] = e;
else
{
for (j = L.length - 1; j >= i; --j)
{
L.data[j + 1] = L.data[j];
}
L.data[j] = e;
}
++L.length;
}
else
cout << "空间已满" << endl;
return L;
}
//删除元素
list DeleteList(list L, int i)
{
int temp;;
if (L.length == 0||i>L.length )
cout << "表为空/超出范围,无法删除" << endl;
else
{
//temp = L.data[i-1];
for (int j = i - 1; j <= L.length - 1; j++)
L.data[j] = L.data[j + 1];
}
L.length--;
return L;
}
int main()
{
//初始化顺序
list L;
int n;
cout << "输入元素个数:";
cin >> n;
CreateList(&L, n);
//求表长
int k=Length(L);
cout << "表长为:" << k<<endl;
//输出表中元素
IsFull(L);
IsFull( L);
cout << "表中元素是:";
ShowList(L);
//按位置查找元素
cout << "输入元素位置:";
int m,f;
cin >> m;
f=SearchList(L,m);
cout << "元素是:"<<f << endl;
//按元素查找位置
cout << "输入要查找的元素; ";
int e;
cin >> e;
int q = VSearchList( L, e);
cout <<"元素位置:"<< q << endl;
//求元素前驱和后继
cout << "输入元素:";
int e2;
cin >> e2;
int q2 = FirstSearchList(L, e2);
int q3 = NextSearchList(L, e2);
cout << "该元素的前驱是:" << q2 <<' '<<"后继是:"<<q3<< endl;
//插入元素
cout << "输入插入元素的位置和数值:";
int i, e3;
cin >> i >> e3;
list q4 = InsertList(L, i, e3);
cout << "插入后的所有元素:";
ShowList(q4);
//删除元素
cout << "输入删除元素的位置:";
int i2;
cin >> i2;
list q5 = DeleteList(q4, i2);
cout << "删除后的所有元素:";
ShowList(q5);
return 0;
}