#include<stdlib.h>
#include <iostream>
using namespace std;
#define MAX_SIZE 100
typedef struct {
int* elems;//顺序表地址
int length;//顺序表长度
int size;//顺序表的空间
}SqList;
bool InitList(SqList& L);//顺序表的初始化
bool listAppend(SqList& L, int e);//顺序表的增加
bool listIsert(SqList& L, int i, int e);//顺序表的插入
bool listDelete(SqList& L, int i);//顺序表删除元素
void destroyList(SqList& L);//顺序表摧毁
void menuShow();
int menuChoise();
void listPrint(SqList& L) {
cout << "顺序表存储空间size:" << L.size << ",已保存元素的个数length:" << L.length << endl;
for (int i = 0; i < L.length; i++) {
cout << L.elems[i] << " ";
}
cout << endl;
}
int main() {
SqList list;
int i, e;
int count = 0;
while (1) {
menuShow();
int n = menuChoise();
switch (n) {
case 1:
cout << "顺序表初始化....!" << endl;
if (InitList(list)) {
cout << "顺序表初始化成功!" << endl;
}
listPrint(list);
break;
case 2:
cout << "请输入要添加的元素个数:";
std::cin >> count;
for (int i = 0; i < count; i++) {
cout << "\n请输入要添加的元素e:";
std::cin >> e;
if (listAppend(list, e)) {
cout << "添加成功!" << endl;
}
else {
cout << "添加失败!" << endl;
}
}
listPrint(list);
break;
case 3: // 3.插入元素
cout << "请输入要插入的位置和要插入的元素";
std::cin >> i >> e;
if (listIsert(list, i, e)) {
cout << "插入成功!" << endl;
}
else {
cout << "插入失败!" << endl;
}
listPrint(list);
break;
case 4: //4.删除元素
cout << "请输入要删除元素的位置:";
std::cin >> i;
if (listDelete(list, i)) {
cout << "删除成功!" << endl;
}
else {
cout << "删除失败!" << endl;
}
listPrint(list);
break;
case 5: //5.销毁
destroyList(list);
break;
}
system("pause");
}
}
bool InitList(SqList& L) {
L.elems = new int[MAX_SIZE];
if (!L.elems) return false;
L.length = 0;
L.size = MAX_SIZE;
return true;
}
//顺序表元素的增加
bool listAppend(SqList& L, int e)
{
if (L.length>=L.size) return false;//储存空间已满
L.elems[L.length] = e;
L.length++;
return true;
}
bool listIsert(SqList& L, int i, int e)
{
if(i<1||i>L.length+1) return false;
if (L.length >= MAX_SIZE) return false;
for (int j = L.length - 1; j >= i-1; j--) {
L.elems[j + 1] = L.elems[j];
}
L.elems[i-1] = e;
L.length++;
return true;
}
bool listDelete(SqList& L, int i)
{
if(i<0||i>=L.length) return false;
if (i == L.length - 1) {
L.length--;
return true;
}
for (int j = i; j < L.length - 1; j++) {
L.elems[j] = L.elems[j + 1];
}
L.length--;
cout << "删除成功" << endl;
return true;
}
void destroyList(SqList& L)
{
if (L.elems) delete []L.elems;
L.length = 0;
L.size = 0;
}
void menuShow()
{
system("cls");
cout << "1.顺序表的初始化" << endl;
cout << "2.顺序表的添加" << endl;
cout << "3.顺序表的插入" << endl;
cout << "4.顺序表的删除" << endl;
cout << "5.顺序表的销毁" << endl;
}
int menuChoise(void) {
int n = 0;
while (1) {
cin >> n;
if (cin.fail()) {
cin.clear();
cin.sync();
cout << "无效输入. 请重新输入." << endl;
system("pause");
}
else {
break;
}
}
return n;
}
![顺序表的]删除](https://img-blog.csdnimg.cn/20210323080916386.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQ2Mzc2ODM0,size_16,color_FFFFFF,t_70)