取栈顶元素、插入、删除栈元素
#include<iostream>
#include<cstdlib>
#define SElemType int
#define Status int
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW 0
using namespace std;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status StackInit(SqStack &S){
S.base=(SElemType*)malloc(sizeof(SElemType)*STACK_INIT_SIZE);
if(!S.base) exit(OVERFLOW);
S.top=S.base;//栈空
S.stacksize=STACK_INIT_SIZE;
return OK;
}
Status GetTop(SqStack S,int &e){
//栈空
if(S.base==S.top) return ERROR;
e=*(S.top-1);
return OK;
}
Status StackInsert(SqStack &S,int &e){
//栈满
if(S.top-S.base>=S.stacksize){
S.base=(SElemType*)realloc(S.base,sizeof(SElemType)*(S.stacksize+STACKINCREMENT));
if(!S.base) exit(OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}
Status StackDelete(SqStack &S,int &e){
//如果栈空
if(S.base==S.top) return ERROR;
e=*--S.top;
return OK;
}
int main(){
SqStack S;
StackInit(S);
int n,x,e;
cout<<"插入的数的个数:";
cin>>n;
cout<<"插入的数为:";
for(int i=0;i<n;i++){
cin>>x;
StackInsert(S,x);
}
cout<<"当前的数为: ";
//遍历栈
int *p=S.base;
for(;p!=S.top;p++){
cout<<*p<<" ";
}
//得到栈顶元素
cout<<endl<<endl<<"栈顶元素为:";
GetTop(S,e);
cout<<e<<endl;
//添加元素
cout<<endl<<"添加元素:";
cin>>x;
StackInsert(S,x);
cout<<"此时的栈为:";
for(p=S.base;p!=S.top;p++){
cout<<*p<<endl;
}
//删除元素
cout<<endl<<endl<<"删除操作"<<endl;
StackDelete(S,e);
cout<<"删除元素为: "<<e<<endl;
cout<<"此时的栈为: ";
for(p=S.base;p!=S.top;p++) cout<<*p<<" ";
}