使用自定义函数
#include<iostream>
#include<stdlib.h>using namespace std;
int top=0; //全局顶端
int stack[6]; //全局
int push(int data)
{
if(top<=5)
{ stack[top++]=data;return 1;}
else
{ cout<<"栈已满";return 0;}
}
int isempty()
{
if(top==0)
return 1;
else
return 0;
}
int pop()
{
if(top>=0)
return stack[--top];
else
{
cout<<"栈已空";
return 0;
}
}
int main()
{
int value;
cout<<"请输入"<<endl;
for(int i=0;i<6;i++)
{
cin>>value;
push(value);
}
cout<<"输出"<<endl;
while(!isempty())
{
cout<<pop();
}
system("pause");
return 0;
}
使用stack容器
#include<iostream>
#include<stdlib.h>
#include<stack>
using namespace std;
int main()
{
stack<int> s;
int value;
for(int i=0;i<6;i++)
{
cin>>value;
s.push (value);
}
for(int i=0;i<6;i++)
{
cout<<s.top (); //top是返回栈顶元素,但不删除栈顶值
s.pop (); //pop是删除栈顶元素,但不返回值
}
system("pause");
return 0;
}