注意栈顶指针为初始设为0和设为1的区别
#include<iostream>
using namespace std;
#define MaxSize 100
typedef int ElemType ;
typedef struct stack{
ElemType data[MaxSize];
int top;
}stack;
void InitStack(stack &s){
s.top=-1;
return ;
}
bool isEmpty(stack s){
if(s.top==-1)
return true;
else
return false;
}
bool push(stack &s,ElemType e){
if(s.top==MaxSize)
return false;
s.data[++s.top] = e;
return true;
}
bool pop(stack &s,ElemType &e){
if(isEmpty(s))
return false;
e = s.data[s.top--];
return true;
}
int getTop(stack s){
return s.data[s.top];
}
int main ()
{
stack s;
InitStack(s);
if(isEmpty(s)) cout<<"空栈!\n";
else cout<<"非空栈!\n";
int i = 1;
while(push(s,i)&&i<=5){
i++;
}
if(isEmpty(s)) cout<<"空栈!\n";
else cout<<"非空栈!\n";
cout<<"栈顶元素:"<<getTop(s)<<endl;
ElemType e;
while(!isEmpty(s)){
pop(s,e);
cout<<"出栈元素:"<<e<<endl;
}
return 0;
}
如有错误,敬请指正!
|