#include <iostream> #include <cstdio> #include <cstdlib> #include <ctime> using namespace std; using ElemType = int; const int MAXSIZE = 20; // 堆栈结构 class Stack { public: ElemType data[MAXSIZE]; int top; }; // 初始化堆栈 void initStack(Stack &stack, int n) { stack.top = -1; srand(time(NULL)); while (n--) { stack.top++; stack.data[stack.top] = rand()%100 + 1; } } // 判空 bool isEmpty(const Stack &stack) { if (stack.top == -1) return true; return false; } // 压栈 void push(Stack &stack, ElemType val) { if (stack.top == MAXSIZE - 1) { cout << "stack is full... "; return; } stack.top++; stack.data[stack.top] = val; } // 出栈 void pop(Stack &stack) { if (isEmpty(stack)) { cout << "stack is empty... "; return; } stack.top--; } // 返回栈顶元素 const ElemType& getTop(const Stack &stack) { if (isEmpty(stack)) { cout << "stack is empty... "; } return stack.data[stack.top]; } // 打印 void print(const Stack &stack) { if (isEmpty(stack)) { cout << "Empty stack... "; } int n = stack.top; cout << "从栈顶到栈底的元素依次为:"; while (n != -1) { cout << stack.data[n--] << " "; } cout << endl; } int main() { Stack stack; initStack(stack, 10); print(stack); pop(stack); print(stack); push(stack, 100); print(stack); cout << "栈顶元素为:" << getTop(stack) << endl; }