顺序表的各项操作(C++版)
- 插入
- 获取
- 删除
- 查找
- 遍历
#include <iostream>
using namespace std;
#define MAXSIZE 100
struct SqList
{
int data[MAXSIZE];
int length;
};
typedef struct SqList SqList;
void createSqList(SqList &L)
{
cout << "请输入你要创建的顺序表长度:" << endl;
cin >> L.length;
cout << "请输入" << L.length << "个数据" << endl;
for (int i = 0; i < L.length; i++)
{
cin >> L.data[i];
}
}
int GetElem(SqList L, int i, int* e)
{
if (i < 1 || i > L.length || L.length == 0)
{
cout << "操作失败!你查找的位置不存在" << endl;
return 0;
}
*e = L.data[i - 1];
cout << "查找成功!第" << i << "号位置的元素数值为:" << *e << endl;
return 1;
}
void GetFunction(SqList L)
{
int i = 0;
cout << "请输入查找第几号位置:" << endl;
cin >> i;
GetElem(L, i, L.data);
}
int insertSqList(SqList& L, int i, int e)
{
if (L.length == MAXSIZE)
{
cout << "顺序表已满!插入失败!" << endl;
return 0;
}
if (i < 1 || i > L.length + 1)
{
cout << "插入位置不合法!插入失败!" << endl;
return 0;
}
int k;
if (i <= L.length)
{
for(k = (L.length - 1); k >= (i - 1); k--)
{
L.data[k + 1] = L.data[k];
}
}
L.data[i - 1] = e;
L.length++;
cout << "操作成功!" << endl;
return 1;
}
void insertFunction(SqList& L)
{
int i = 0;
cout << "请输入你要插入的位置:" << endl;
cin >> i;
int e = 0;
cout << "请输入你要插入的数值:" << endl;
cin >> e;
insertSqList(L, i, e);
}
int deleteElem(SqList& L, int i, int* e)
{
if (L.length == 0)
{
cout << "删除失败!请先创建顺序表!" << endl;
return 0;
}
if (i < 1 || i > L.length)
{
cout << "删除失败!删除位置不合法!" << endl;
return 0;
}
*e = L.data[i - 1];
int k;
if (i < L.length)
{
for (k = (i - 1); k < (L.length - 1); k++)
{
L.data[k] = L.data[k + 1];
}
}
L.length--;
return 1;
}
void deleteFunction(SqList& L)
{
int i;
cout << "请输入你要删除第几号元素:" << endl;
cin >> i;
int recovery;
deleteElem(L, i, &recovery);
cout << "被删除的数值是:" << recovery << endl;
}
int locateElem(SqList L, int e)
{
for (int i = 0; i < L.length; i++)
{
if (e == L.data[i])
{
cout << "查找成功!元素在" << (i + 1) << "号位置" << endl;
return 1;
}
}
cout << "查找失败!没有此元素!" << endl;
return 0;
}
void locateElem(SqList L)
{
int Elem;
cout << "请输入你要查找的元素数值:" << endl;
cin >> Elem;
locateElem(L, Elem);
}
void printSqList(SqList L, int len)
{
cout << "遍历的结果为:" << endl;
for (int i = 0; i < len; i++)
{
cout << L.data[i] << " ";
}
cout << endl;
}
void showMenu()
{
cout << "============================" << endl;
cout << "========1.创建顺序表========" << endl;
cout << "========2.获取元素值========" << endl;
cout << "========3.插入元素值========" << endl;
cout << "========4.删除元素值========" << endl;
cout << "========5.定位元素值========" << endl;
cout << "========6.输出顺序表========" << endl;
cout << "=========0.退出使用=========" << endl;
cout << "============================" << endl;
}
int main()
{
SqList L;
int selection = 0;
while (true)
{
showMenu();
cin >> selection;
switch (selection)
{
case 1:
createSqList(L);
break;
case 2:
GetFunction(L);
break;
case 3:
insertFunction(L);
break;
case 4:
deleteFunction(L);
break;
case 5:
locateElem(L);
break;
case 6:
printSqList(L, L.length);
break;
case 0:
cout << "欢迎下次使用!" << endl;
system("pause");
break;
default:
break;
}
}
system("pause");
return 0;
}