#include <iostream>
#define MaxSize 100
using namespace std;
struct MyStruct
{
int Data[MaxSize];
int Length;//表中现有元素的个数
}L;
//初始化
void InitList(MyStruct& L) {
for (int i = 0; i < MaxSize; i++) {
L.Data[i] = 0;
L.Length = 0;
}
}
//显示菜单
void ShowMenu() {
system("pause");
system("cls");
cout << "***************************" << endl;
cout << "**** 1.新增数据 ****" << endl;
cout << "**** 2.删除数据 ****" << endl;
cout << "**** 3.更改数据 ****" << endl;
cout << "**** 4.查询数据 ****" << endl;
cout << "**** 5.显示所有 ****" << endl;
cout << "**** 6.插入数据 ****" << endl;
cout << "**** 7.退出系统 ****" << endl;
cout << "***************************" << endl;
cout << "请输入你的选择:" << endl;
}
//1.新增数据
void AddData(MyStruct& L) {
int Num, Data;
cout << "请输入需要添加数据的个数:";
cin >> Num;
if (Num <= MaxSize) {
for (int i = 0; i < Num; i++) {
cout << "请输入第" << i + 1 << "个数据:";
cin >> Data;
L.Data[i] = Data;
L.Length++;
}
cout << "成功添加" << Num << "个数据!" << endl;
}
else {
cout << "输入数据有误!!!" << endl;
return;
}
}
//2.删除数据
void DeleteData(MyStruct& L) {
int Num;
cout << "请输入需要删除数据的位序:";
cin >> Num;
if (Num<1 || Num>L.Length) {
cout << "输入数据有误!!!" << endl;
return;
}
for (int i = Num; i < L.Length; i++) {
L.Data[i - 1] = L.Data[i];
}
L.Length--;
cout << "删除数据成功!!" << endl;
return;
}
//3.更改数据
void ChangeData(MyStruct& L) {
int Num, Data;
cout << "请输入需要更改数据的位序:";
cin >> Num;
if (Num <= L.Length) {
cout << "需要将其改为:";
cin >> Data;
L.Data[Num - 1] = Data;
cout << "修改成功!" << endl;
}
else {
cout << "输入数据有误!!!" << endl;
return;
}
}
//4.查询数据
void Enquire(MyStruct& L) {
int Num;
cout << "请输入需要查询数据的位序:";
cin >> Num;
if (Num <= L.Length) {
cout << "位序为" << Num << "的数据是:" << L.Data[Num - 1] << endl;
cout << "查询数据成功" << endl;
}
else {
cout << "输入数据有误!!!" << endl;
return;
}
}
//5.显示所有
void ShowAll(MyStruct& L) {
for (int i = 0; i < L.Length; i++) {
cout << L.Data[i] << "\t";
}
cout << endl;
}
//6.插入数据
void Insert(MyStruct& L) {
int Num, Data;
cout << "请输入插入数据的位序:";
cin >> Num;
if (Num <= L.Length && L.Length + 1 < MaxSize) {
cout << "请输入需要插入的数据:";
cin >> Data;
for (int i = L.Length - 1; i >= Num - 1; i--) {
L.Data[i + 1] = L.Data[i];
}
L.Data[Num - 1] = Data;
L.Length++;
cout << "插入数据成功!!" << endl;
}
else {
cout << "输入数据有误!!!" << endl;
return;
}
}
//7.退出系统
void ExitSystem() {
cout << "欢迎下次使用" << endl;
exit(0);
}
int main() {
int Count = 0;
InitList(L);
while (true)
{
switch (Count) {
case 1:
AddData(L);
ShowMenu();
cin >> Count;
break;
case 2:
DeleteData(L);
ShowMenu();
cin >> Count;
break;
case 3:
ChangeData(L);
ShowMenu();
cin >> Count;
break;
case 4:
Enquire(L);
ShowMenu();
cin >> Count;
break;
case 5:
ShowAll(L);
ShowMenu();
cin >> Count;
break;
case 6:
Insert(L);
ShowMenu();
cin >> Count;
break;
case 7:
ExitSystem();
break;
default:
ShowMenu();
cin >> Count;
break;
}
}
return 0;
}
顺序表的基本操作
于 2022-04-08 10:03:07 首次发布