#include <iostream>
using namespace std;
typedef int stackEntry;
const int maxstack = 100;//栈的最大尺寸
class stack{
public:
stack();
void pop();
void push(const stackEntry &item);
void top(stackEntry &item) const;
bool empty() const;
private:
int count;
stackEntry data[maxstack];
};
void stack::push(const stackEntry &item)//如果栈未满,将元素item压入栈顶,否则报错
{
if(count>=maxstack)
cout<<"栈上溢,无法压入元素。";
else
data[count++] = item;
}
void stack::pop()//如果栈未空,将栈顶元素删除,否则报错
{
if(count == 0)
cout<<"栈下溢,无法弹出元素。";
else
--count;
}
void stack::top(stackEntry &item) const//如果栈未空,将栈顶元素取出放在item里,否则报错
{
if(count == 0)
cout<<"栈下溢,无法读取元素。";
else
item = data[count - 1];
}
bool stack::empty() const //判断栈是否为空
{
if(count > 0)
return false;
return true;
}
stack::stack()//构建函数,初始化一个空栈
{
count = 0;
}
//乘坐校园通勤车
int main()
//输入:用户提供数值n,代表n个乘客和n个乘客的编号
//输出:将乘客的编号倒着输送出来
{
int n;
int item;
stack passenger; //定义一个栈,名字是passagers
cout<<"输入乘客人数n"<<endl;
cin>>n;
cout<<"按登车顺序输入乘客编号"<<endl;
for(int i = 0;i<n;i++)
{
cin>>item;
passenger.push(item);
}
cout<<endl<<endl;
cout<<"乘客下车的顺序是:";
while(!passenger.empty()){
passenger.top(item);
cout<<item<<" ";
passenger.pop();
}
cout<<endl;
return 0;
}