【教程】手把手教你實現(xiàn)數(shù)據(jù)結構順序表(2)!

#include <iostream>
//順序表
#define maxLen 100
using namespace std;
typedef struct elemType {
int elemNo;
string elemName;
}elemType;
typedef struct sqList {
elemType data[maxLen];
int length;
}sqList;
void initList(sqList &sq){
cout<<endl<<"初始化&清除成功!"<<endl;
sq.length = 0;
}
int isPok(sqList sq){
cout<<"請輸入要操作的位置:";
int p = 1;
cin>>p;
if(p>=1&&p<=sq.length){
return p;
}
cout<<"輸入的位置不合法!";
return -1;
}
void allList(sqList sq) { //遍歷數(shù)據(jù)
cout<<endl<<"遍歷結果如下:"<<endl;
cout<<"elemNo"<<" "<<"elemName"<<endl;
for(int i = 0;i<sq.length;i++){
cout<<sq.data[i].elemNo<<" "<<sq.data[i].elemName<<endl;
}
cout<<"當前數(shù)據(jù)個數(shù)為:"<<sq.length<<"個"<<endl;
}
void addList(sqList &sq, elemType elem) {//增
if(sq.length>=0 && sq.length<maxLen-1){
elem.elemNo=sq.length;
sq.data[sq.length++] = elem;
cout<<"添加成功!"<<endl;
}
else cout<<"當前順序表已滿??!"<<endl;
}
void delList(sqList &sq) {//刪
int p = isPok(sq);
if(p == - 1){
cout<<"刪除失敗!";
return;
}
else {
for (int i = p; i<sq.length; i++){
sq.data[i-1] = sq.data[i];
}
sq.length--;
cout<<"刪除成功!";
}
}
elemType setAndGetEmem(int elemNo, string elemName) {
elemType elem;
elem.elemNo = elemNo;
elem.elemName = elemName;
return elem;
}
void changeList(sqList &sq) {//改
int p = isPok(sq);
if(p == -1){
cout<<"失?。?#34;;
return;
}
else{
sq.data[p-1] = setAndGetEmem(10086,"中國移不動");
cout<<"修改成功!";
}
}
elemType getList(sqList sq) {//查
elemType t;
int p = isPok(sq);
if(p == -1){
cout<<"查詢失敗!";
return t;
}
else{
cout<<"查詢成功!結果為:"<<endl;
cout<<sq.data[p-1].elemNo<<" "<<sq.data[p-1].elemName<<endl;
t = sq.data[p-1];
return t;
}
}
void menu (){
cout<<endl<<"\n1.初始化&清除順序表\n2.增加數(shù)據(jù)\n3.刪除數(shù)據(jù)\n4.修改數(shù)據(jù)\n5.查詢數(shù)據(jù)\n6.遍歷數(shù)據(jù)\n7.退出"<<endl;
cout<<"請輸入選項: "<<endl;
}
int main() {
sqList sq; //聲明變量
while(1){
menu();
int choice = 1;
cin>>choice;
switch(choice){
case 1:initList(sq);//初始化
break;
case 2:addList(sq, setAndGetEmem(1, "test")); //增
break;
case 3:delList(sq); //刪
break;
case 4:changeList(sq); //改
break;
case 5:getList(sq); //查
break;
case 6:allList(sq); //遍歷
break;
case 7:cout<<"已退出?。?#34;;return 0;
default: cout<<"輸入有誤!"<<endl;
}
}
return 0;
}