初始化 int InitList_Sq(SqList &L)
创建 void CreateList(SqList &L,int a[],int n)
显示 void ShowList(SqList &L)
判断是否为空表 int IsEmpty(SqList &L)
求表长 int GetLength(SqList &L)
取元素 int GetElem(SqList &L,int i,int &e)
查找 int LocateElem(SqList &L,int e)
插入 int ListInsert_Sq(SqList &L,int i,int e)
删除 int ListDelete_Sq(SqList &L,int i)
清空---->判断是否为空表 void ClearList(SqList &L)
销毁表 void DestroyList(SqList &L)
#include<iostream>
using namespace std;
#define MAXSIZE 100
#define OK 1
#define OVERFLOW -2
#define ERROR 0
typedef struct{
int* elem;
int length;
}SqList;
//初始化
int InitList_Sq(SqList &L){
L.elem=new int[MAXSIZE];
if(!L.elem) exit(OVERFLOW);
L.length=0;
return OK;
}
//创建表
void CreateList(SqList &L,int a[],int n){
for(int i=0;i<n;i++){
L.elem[i]=a[i];
L.length++;
}
}
//显示表
void ShowList(SqList &L){
cout<<"表长为:"<<L.length<<endl;
for(int i=0;i<L.length;i++){
cout<<L.elem[i]<<' ';
}
cout<<endl;
}
//判断是否为空表
int IsEmpty(SqList &L){
if(L.length==0) return 1;
else return 0;
}
//求表长
int GetLength(SqList &L){
return(L.length);
}
//取元素
int GetElem(SqList &L,int i){
if(i<1||i>L.length) return ERROR;
return L.elem[i-1];
}
//查找元素
int LocateElem(SqList &L,int e){
for(int i=0;i<L.length;i++){
if(L.elem[i]==e) return i+1;
}
return 0;
}
//插入元素
int InsertList_Sq(SqList &L,int i,int 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;
}
//删除元素
int DeleteList_Sq(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 ClearList(SqList &L){
L.length=0;
}
//销毁表
void DestroyList(SqList &L){
if(L.elem) delete(L.elem);
}
int main(){
SqList L;
int a[]={23,43,31,65,7,64,76,87,56,88};
InitList_Sq(L);
CreateList(L,a,10);
ShowList(L);
//对线性表进行操作
cout<<endl<<"——————基本操作————————"<<endl;
cout<<"是否为空表?(1为空,0不为空):"<<IsEmpty(L)<<endl;
cout<<"表长为:"<<GetLength(L)<<endl;
cout<<"表中第4个元素为:"<<GetElem(L,4)<<endl;
cout<<"表中是否能查找到元素88?(若找到返回位置):"<<LocateElem(L,88)<<endl;
//插入删除
cout<<endl<<"——————插入删除操作————————"<<endl;
InsertList_Sq(L,5,100);
cout<<"插入后的表为:"<<endl;
ShowList(L);
DeleteList_Sq(L,5);
cout<<"删除后的表为:"<<endl;
ShowList(L);
//清空销毁
cout<<endl<<"——————清空销毁表————————"<<endl;
ClearList(L);
cout<<"是否为空表?(1为空,0不为空):"<<IsEmpty(L)<<endl;
DestroyList(L);
return 0;
}
运行结果如图: