#include <iostream>
using namespace std;
// 順序表的結構體
#define MAXSIZE 50
// 資料元素結構體
typedef struct
{
int x;
}ElemType;
// 靜态順序表
typedef struct
{
ElemType data[MAXSIZE];//資料
int length;//資料大小
}SqList;
class MySqList{
public:
MySqList(){
l.length=0;
cout<<"初始化完成"<<endl;
}
void Travel();//周遊順序表
bool ListInert(int loc,ElemType e);//插入資料
bool ListDelete(int loc,ElemType &e);//删除資料
int LocateElem(ElemType e);//确定元素位置
void chice();//功能選擇
private:
SqList l;
};
//周遊順序表
void MySqList::Travel(){
for(int i=0;i<l.length;i++){
cout<<l.data[i].x<<" ";
}
cout<<endl<<"=========================="<<endl;
}
// 插入資料
bool MySqList::ListInert(int loc,ElemType e){
//判斷插入位置是否錯誤
if(loc<0||loc>l.length+1){
return false;
}
//判斷順序表是否滿
if(l.length>=MAXSIZE){
return false;
}
//可以插入右移
for(int i=l.length;i>=loc;i--){
l.data[i]=l.data[i-1];
}
//插入
l.data[loc-1]=e;
l.length++;
return true;
}
// 删除資料
bool MySqList::ListDelete(int loc,ElemType &e){
//判斷删除位置是否錯誤
if(loc<1||loc>l.length){
return false;
}
//删除資料的值
e=l.data[loc-1];
//左移
for(int i=loc-1;i<l.length-1;i++){
l.data[i]=l.data[i+1];
}
l.length--;
return true;
}
//确定元素位置
int MySqList::LocateElem(ElemType e){
for(int i=0;i<l.length;i++){
if(l.data[i].x==e.x){
return i+1;
}
}
return 0;
}
//功能選擇
void MySqList::chice(){
while(true){
cout<<"0-----退出"<<endl;
cout<<"1-----周遊"<<endl;
cout<<"2-----插入"<<endl;
cout<<"3-----删除"<<endl;
cout<<"4-----确定元素位置"<<endl;
cout<<"請輸入功能選擇"<<endl;
int c;
cin>>c;
int loc;
ElemType e;
switch(c){
case 0:
cout<<"退出程式"<<endl;
return;
case 1:
Travel();
break;
case 2:
cout<<"請輸入插入位置"<<endl;
cin>>loc;
cout<<"請輸入資料"<<endl;
cin>>e.x;
ListInert(loc,e);
break;
case 3:
cout<<"請輸入删除位置"<<endl;
cin>>loc;
cout<<"删除元素為"<<endl;
ListDelete(loc,e);
cout<<e.x;
break;
case 4:
cout<<"請輸入元素"<<endl;
cin>>e.x;
cout<<"元素位置為"<<LocateElem(e)<<endl;
break;
default:
cout<<"輸入格式不正确"<<endl;
break;
}
}
}
int main()
{
MySqList l;
l.chice();
return 0;
}