根据命令提示进行顺序表的基本操作(待完善)
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXSIZE 1000
#define OVERFLOW -2
#define ERROR 1
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType* elem;
int length;
}SqList;
void InitList(SqList& L)
{
L.elem = new ElemType[MAXSIZE];
if (L.elem == NULL)
{
cout << "存储空间分配失败!" << endl;
exit(OVERFLOW);
}
L.length = 0;
cout << "顺序表初始化完成" << endl;
}
void Create(SqList& L, int n, ElemType e)
{
cout << "请输入" << n << "个顺序表中的元素" << endl;
for (int i = 0; i < n; i++)
{
ElemType e;
cin >> e;
L.elem[i] = e;
L.length++;
}
}
int Print(SqList L)
{
if (L.length == 0)
{
cout << "顺序表中无元素" << endl;
return 1;
}
for (int k = 0; k < L.length; k++)
{
if (k == L.length - 1)
{
cout << L.elem[k];
}
else
{
cout << L.elem[k] << ' ';
}
}
}
int Insert(SqList& L, int i, ElemType e)
{
cout << "请输入要插入的元素及插得的位置" << endl;
cin >> e >> i;
if ((i < 1) || (i > L.length + 1))
{
cout << "插入地址不合法" << endl;
return ERROR;
}
if (L.length == MAXSIZE)
{
cout << "存储空间已满" << endl;
return ERROR;
}
for (int j = L.length - 1; j >= i - 1; j--)
{
L.elem[j + 1] = L.elem[j];
}
L.elem[i - 1] = e;
++L.length;
}
int Delete(SqList& L, int i) {
cout << "请输入要删除元素的位置" << endl;
cin >> i;
if((i < 1) || (i > L.length + 1))
{
cout << "删除地址不合法" << endl;
return ERROR;
}
for (int j = i; j <= L.length; j++)
{
L.elem[j - 1] = L.elem[j];
}
--L.length;
}
void Sort(SqList& L)
{
sort(L.elem, L.elem + L.length);
}
int main()
{
int n, x,i=0,p=0;
cout << "请输入数组长度n的值" << endl;
cin >> n;
SqList L;
ElemType e=0;
InitList(L);
do
{
cout << "请选择您想进行的操作" << endl;
cout << "0.给顺序表读入值" << endl;
cout << "1.给顺序表插入值" << endl;
cout << "2.给顺序表删除值" << endl;
cout << "3.给顺序表排序" << endl;
cout << "4.输出顺序表" << endl;
cin >> x;
switch (x) {
case 0: {
Create(L, n, e);
cout << "退出请按1,输入其他数字返回上级清单" << endl;
cin >> p;
break; }
case 1: {
Insert(L, i, e);
cout << "退出请按1,输入其他数字返回上级清单" << endl;
cin >> p;
break;
}
case 2: {
Delete(L, i);
cout << "退出请按1,输入其他数字返回上级清单" << endl;
int p;
cin >> p;
break;
}
case 3: {
Sort(L);
cout << "退出请按1,输入其他数字返回上级清单" << endl;
cin >> p;
break;
}
case 4: {
Print(L);
cout << "退出请按1,输入其他数字返回上级清单" << endl;
cin >> p;
break;
}
}
} while (p!=1);
}