#include<iostream>
using namespace std;
//定义顺序表的结构
struct SeqList;
typedef SeqList *pSeqList;
struct SeqList{
int MAXSIZE;
int n;
char *element;
};
//创建空顺序表
pSeqList createNullList_seq(int m){
pSeqList palist = new SeqList;
if(palist != NULL){
palist->element = (char*)malloc(m * sizeof(char));
if(palist->element){
palist->MAXSIZE = m;
palist->n = 0;
return palist;
}else free(palist);
cout<<"创建失败!"<<endl;
return NULL;
}
}
//判断空表
int isNullList_seq(pSeqList palist){
return (palist->n == 0);
/*if(palist->n == 0)return 1;
else return 0;*/
}
//输入顺序表,以#结束
void input(pSeqList palist){
char p;
while(true){
cin>>p;
if(p == '#')break;
palist->element[palist->n] = p;
palist->n ++;
}
}
//读表中的值
void show(pSeqList palist){
for(int i = 0; i < palist->n; i++){
cout<<palist->element[i];
cout<<" ";
}
cout<<endl;
}
//查找元素的下标
int Locata_seq(pSeqList palist,char x){
for(int i = 0; i < palist->n; i ++){
if(palist->element[i] == x)
return i+1;
}
return -1;
}
//在下标p处插入元素
int insertPre_seq(pSeqList palist,int p,char x){
p = p-1;
if(palist->n >= palist->MAXSIZE){
cout<<"溢出!"<<endl;
return 0;
}
if(p < 0 || p > palist->n){
cout<<"不存在p点!"<<endl;
return 0;
}
for(int i = palist->n - 1;i >= p ;i--){
palist->element[i+1] = palist->element[i];
}
palist->element[p] = x;
palist->n = palist->n + 1;
return 1;
}
//删除元素
int deleteP_seq(pSeqList palist,int p){
if(p < -1 || p - 1 > palist->n){
cout<<"不存在p点!"<<endl;
return 0;
}
for(int i = p-1; i < palist->n -1;i ++){
palist->element[i] = palist->element[i+1];
}
palist->n = palist->n -1;
return 1;
}
int main(){
//测试功能
pSeqList l = createNullList_seq(10);//创建空表
pSeqList q = createNullList_seq(10);
input(q);
cout<<isNullList_seq(q)<<endl;//非空表为0
cout<<isNullList_seq(l)<<endl;//空表为1
show(q);
deleteP_seq(q,2);
show(q);
cout<<Locata_seq(q,'o')<<endl;
insertPre_seq(q,5,'l');
show(q);
system("pause");
return 0;
}
顺序表的简单操作
最新推荐文章于 2021-10-08 23:32:38 发布