代码如下
#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
#define maxsize 100
//定义栈的结构体
typedef int datatype;
struct Stack{
datatype elements[maxsize];
int Top;
};
//对栈初始化
struct Stack *SetNullS(struct Stack *S){
S->Top=-1;
return S;
}
//判断栈是否为空(出栈时)
int EmptyS(struct Stack *S){
if(S->Top>=0) return 0;
else return 1;
}
//进栈,需要判断是否栈满
struct Stack *PushStackS(struct Stack *S,datatype e){
if(S->Top>=maxsize-1){ //数组从0开始
cout<<"溢出"<<endl;
return NULL;
}
else{
S->Top++;
S->elements[S->Top]=e;
}
return S;
}
//出栈,需要判断是否栈空,并返回栈顶元素
datatype *PopS(struct Stack *S){
datatype *ret;
if(EmptyS(S)){
cout<<"栈为空"<<endl;
return NULL;
}
else{
S->Top--; //删除栈顶数据元素
ret=(datatype *)malloc(sizeof(datatype));
*ret=S->elements[S->Top+1];
return ret;
}
}
//取栈顶元素(仅取值)
datatype *GetTopS(struct Stack *S){
datatype *ret;
if(EmptyS(S)){
cout<<"栈是空的"<<endl;
return NULL;
}
else{
ret=(datatype *)malloc(sizeof(datatype));
*ret=S->elements[S->Top];
return ret;
}
}
int main(){
struct Stack *S;
SetNullS(S); //初始化
datatype e;
while((e=getche())!='#') //入栈
{
PushStackS(S,e);
}
cout<<endl;
datatype *x=GetTopS(S); //取栈顶元素
cout<<x<<endl;
PopS(S); //出栈
datatype *y=GetTopS(S); //取栈顶元素
cout<<y<<endl;
return 0;
}
最后输出的应该是数值的,结果输出了地址,为什么?