数据结构中栈的基本操作(顺序存储结构)
初始化,判断栈空,压栈,出栈,取栈顶元素
下面展示 代码
。
# include <iostream>
# include <stdlib.h>
using namespace std;
# define MAX 20
struct z{
int data[MAX];
int top;
};//定义栈结构体,
struct z* init_f(){
struct z *s;
s=(struct z *)malloc(sizeof(struct z ));
if(!s){
cout<<"空间不足!";
return NULL;
}
else{
s->top=-1;
return s;
}
}//栈的初始化
int empty_f(struct z *s){
if(s->top==-1)
return 1;
else
return 0;
}//判断空栈
int push_f(struct z *s,int a){
if(s->top==MAX-1){
return 0;
}
else{
(s->top)+=1;
s->data[s->top]=a;
return 1;
}
}//压栈
int pop_f(struct z*s,int *x){
if(empty_f(s))
return 0;
else{
*x=s->data[s->top];
(s->top)-=1;
return 1;
}
}//出栈
int top_f(struct z*s){
if(empty_f(s))
return 0;
else{
return s->data[s->top];
}
}//取栈顶元素
int main(){
struct z *s=init_f();
int i;int x1;
for(i=0;i<MAX;++i){
if(!push_f(s,i))
break;
}
pop_f(s,&x1);
int x2=top_f(s);
if(x1==x2+1)
cout<<x1<<">"<<x2<<endl<<"Perfect!"<<endl;
cout<<s->top<<endl;
free(s);
return 0;
}