#include<iostream>
using namespace std;
#define MAXSIZE 5
typedef int ElemType;
typedef struct{
ElemType data[MAXSIZE];//数组
int length;//线性表长度
}SqList;
#define OK 1
#define ERROR 0
typedef int Status;
Status InitList(SqList *L){
// for(int i=0;i<L->length;i++){
// L->data[i]=0;
// }
L->length=0;
return OK;
}
//初始化
Status ListEmpty(SqList L){
for(int i=0;i<L.length;i++){
if(L.data[i]!=0){
return ERROR;
}
}
return OK;
}
//判断是否是空表
Status ClearList(SqList *L){
InitList(L);
return OK;
}
//清空线性表
Status GetElem(SqList L,int i,ElemType *e){
if(L.length==0 || i<1 || i>L.length){
//下标越界或数组长度为0,返回ERROR
return ERROR;
}
cout<<L.data[i-1]<<endl;
*e=L.data[i-1];
return OK;
}
//获取元素数据
Status LocateElem(SqList L,int e){
for(int i=0;i<L.length;i++){
if(L.data[i]==e){
return i;
}
}
return -1;
}
//查找元素序号
Status ListInsert(SqList *L,int i,ElemType e){
if(L->length==MAXSIZE){
return ERROR;
}
if(i<0 || i>L->length){
return ERROR;
}
for(int j=L->length;j>i;j--){
L->data[j]=L->data[j-1];
}
L->data[i]=e;
L->length++;
return OK;
}
//插入元素
Status ListDelete(SqList *L,int i,ElemType *e){
if(i<0 || i>L->length){
return ERROR;
}
if(L->length==0){
return ERROR;
}
*e=L->data[i-1];
for(int j=i-1;j<L->length-1;j++){
L->data[j]=L->data[j+1];
}
L->length--;
return OK;
}
//删除元素
Status ListLength(SqList L){
return L.length;
}
//返回线性表长度
Status LookUp(SqList L){
for(int i=0;i<L.length;i++){
cout<<L.data[i]<<" ";
}
cout<<endl;
return OK;
}
//遍历线性表
void menu(){
cout<<">>线性表顺序存储结构<<"<<endl;
cout<<">>0-初始化 1-空表判断<<"<<endl;
cout<<">>2-清空 3-查找数据<<"<<endl;
cout<<">>4-查找序号 5-插入<<"<<endl;
cout<<">>6-删除 7-长度<<"<<endl;
cout<<">>8-退出<<"<<endl;
cout<<endl;
}
int main(){
SqList list;
int flag;
int i;
int j;
int num;
bool active=true;
while(active){
menu();
cout<<"请输入操作:"<<endl;
cin>>flag;
switch(flag){
case 0:
if(InitList(&list)){
cout<<"初始化完毕"<<endl;
}
break;
case 1:
if(ListEmpty(list)){
cout<<"线性表为空"<<endl;
}else{
cout<<"线性表不为空"<<endl;
}
break;
case 2:
ClearList(&list);
cout<<"已清空线性表"<<endl;
break;
case 3:
cout<<"请输入要查找的数据序号:"<<endl;
cin>>i;
if(GetElem(list,i,&num)){
cout<<"第"<<i<<"个元素为"<<num<<endl;
}else{
cout<<"第"<<i<<"个元素不存在"<<endl;
}
break;
case 4:
cout<<"请输入要查找的数据:"<<endl;
cin>>i;
if(LocateElem(list,i)!=-1){
cout<<"数据序号为:"<<LocateElem(list,i)<<endl;
}else{
cout<<"数据"<<i<<"不存在"<<endl;
}
break;
case 5:
cout<<"请输入要插入数据的位置:";
cin>>i;
cout<<"请输入要插入的数据:";
cin>>j;
if(ListInsert(&list,i,j)){
cout<<"插入完成"<<endl;
}else{
cout<<"插入位置错误"<<endl;
}
break;
case 6:
cout<<"请输入要删除的元素序号:";
cin>>i;
num=0;
if(ListDelete(&list,i,&num)){
cout<<"第"<<i<<"个"<<"数据"<<num<<"已删除"<<endl;
}else{
cout<<"第"<<i<<"个"<<"数据不存在"<<endl;
}
break;
case 7:
LookUp(list);
cout<<"线性表的长度为:"<<ListLength(list)<<endl;
break;
case 8:
active=false;
break;
default :
cout<<"请输入正确操作"<<endl;
break;
}
}
return 0;
}