顺序表的实现
#include<iostream> using namespace std; #define MAXSIZE 100 #define OK 1 #define ERROR 0 typedef int status; typedef struct { int a; }pta; typedef struct{ pta *elem; int length; }SqList; status IniList(SqList &L)//构造空顺序表 { L.elem=new pta[MAXSIZE]; if(!L.elem)return ERROR; L.length=0; return OK; } status GetElem(SqList L,int i,pta &e)//获取 { if(i<1||i>L.length) return ERROR; e=L.elem[i-1]; return OK; } int LocateElem(SqList L,pta e)//查找 { for(int i=0;i<L.length;i++) if(L.elem[i].a==e.a) return i+1; return 0; } status ListInsert(SqList &L,int i,pta e)//插入 { if((i<1)||(i>L.length+1))return ERROR; if(L.length==MAXSIZE)return ERROR; for(int j=L.length-1;j>=i-1;j--) L.elem[j+1]=L.elem[j]; L.elem[i-1]=e; ++L.length; return OK; } status ListDelete(SqList &L,int i)//删除 { if((i<1)||(i>L.length))return ERROR; for(int j=i;j<=L.length-1;j++) L.elem[j-1]=L.elem[j]; --L.length; return OK; } void display(SqList &L) { for(int i=0;i<L.length;i++) cout<<L.elem[i].a<<endl; } int main() { int i; SqList L; IniList(L); int mount; pta e; for(;;) { cout<<"遍历0,查询请输入1,查找输入2,插入输入3,删除输入4,退出输入5"<<endl; cin>>mount; if(mount==5) return 0; switch(mount) { case 0: display(L);break; case 1: cout<<"请输入你想获取第几个的数据"<<endl; cin>>i; GetElem(L,i,e); cout<<"其数据为:"<<e.a;break; case 2: cout<<"请输入你想查找的数据"<<endl; cin>>e.a; if(LocateElem(L,e)!=0) { cout<<"该数在第"<<LocateElem(L,e)<<"个"<<endl; } break; case 3: cout<<"请输入你想要插入到第几个位置"<<endl; cin>>i; cout<<"输入插入的数值为:"; cin>>e.a; ListInsert(L,i,e); break; case 4: cout<<"请输入你想删除第几个数据"<<endl; cin>>i; ListDelete(L,i); break; } } }