#include <iostream> using namespace std; typedef int stackEntry; const int overflow = 1; const int underflow = 2; const int success = 0; struct Node { stackEntry data; Node *next; }; class stack { public: stack(); bool empty() const; int push(const stackEntry &item); int pop(); int top(stackEntry &item) const; // void operator = (const stack &original); // stack(const stack &original); protected: Node *top_node; }; stack::stack() { top_node = NULL; } int stack::push(const stackEntry &item) { Node *new_top = new Node; //为元素item构建新的节点,该节点指向原来的栈顶元素 if (new_top == NULL) return overflow; new_top->data = item; new_top->next = top_node; top_node = new_top; return success; } int stack::pop() { Node *old_top = top_node; if (old_top == NULL) { return underflow; } top_node = old_top->next; delete old_top; return success; } int stack::top(stackEntry &item) const { if (top_node == NULL) return underflow; item = top_node->data; return success; } bool stack::empty() const { if (top_node != NULL) return false; return true; } int main()//乘客上下飞机模拟程序 { int n; int item; stack passengers; stack temp; cout << "输入乘客人数n" << endl; cin >> n; cout << "按登机顺序输入乘客编号" << endl; for (int i = 0; i < n; i++) { cin >> item; temp.push(item); } passengers = temp; cout << endl << endl; cout << "乘客下机顺序是:"; while (!passengers.empty()) { passengers.top(item); cout << item << " "; passengers.pop(); } cout << endl; }
时间: 2024-10-10 15:12:58