赞
踩
随机产生10个100以内的整数建立一个顺序栈,从栈顶到栈底依次显示栈内元素;从键盘输入出栈元素个数 n (1<= n <=10),将 n 个元素依次出栈并显示出栈元素,再显示此时栈顶元素。
- #include <iostream>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
- const int StackSize = 100;
- template <typename DataType>
- class SeqStack {
- public:
- SeqStack() : top(-1) {} // 构造函数,初始化栈顶为-1
- DataType data[StackSize];
- int top;
- void Push(DataType x);
- DataType pop();
- int Empty();
- void GenerateAndPushRandomNumbers(); // 生成随机数并压入栈
- void PopAndDisplay(int n); // 出栈并显示n个元素
- void DisplayTop(); // 显示栈顶元素
- };
- template <typename DataType>
- void SeqStack<DataType>::Push(DataType x) {
- if (top == StackSize - 1) throw "Overflow";
- data[++top] = x;
- }
- template <typename DataType>
- DataType SeqStack<DataType>::pop() {
- if (top == -1) throw "下溢";
- return data[top--];
- }
- template <typename DataType>
- int SeqStack<DataType>::Empty() {
- return top == -1;
- }
- template <typename DataType>
- void SeqStack<DataType>::GenerateAndPushRandomNumbers() {
- srand(time(nullptr)); // 初始化随机数种子
- for (int i = 0; i < 10; ++i) {
- int randomNumber = rand() % 100; // 生成0到99的随机数
- Push(randomNumber);
- }
- }
- template <typename DataType>
- void SeqStack<DataType>::PopAndDisplay(int n) {
-
- for (int i = 0; i < n; ++i) {
- DataType poppedElement = pop();
- cout << "Popped element: " << poppedElement << endl;
- }
- }
- template <typename DataType>
- void SeqStack<DataType>::DisplayTop() {
- if (!Empty()) {
- cout << "Top element: " << data[top] << endl;
- }
- else {
- cout << "Stack is empty." << endl;
- }
- }
- int main() {
- SeqStack<int> stack;
- stack.GenerateAndPushRandomNumbers(); // 生成随机数并压入栈
- // 显示栈内元素
- cout << "Elements in the stack (from top to bottom):";
- for (int i = stack.top; i >= 0; --i) {
- cout << " " << stack.data[i];
- }
- cout << endl;
- int n;
- cout << "Enter the number of elements to pop (1-10): ";
- cin >> n;
- stack.PopAndDisplay(n); // 出栈并显示元素
- stack.DisplayTop(); // 显示栈顶元素
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。