当前位置:   article > 正文

算法与数据结构 顺序栈(C++)

算法与数据结构 顺序栈(C++)

随机产生10个100以内的整数建立一个顺序栈,从栈顶到栈底依次显示栈内元素;从键盘输入出栈元素个数 n (1<= n <=10),将 n 个元素依次出栈并显示出栈元素,再显示此时栈顶元素。

  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. using namespace std;
  5. const int StackSize = 100;
  6. template <typename DataType>
  7. class SeqStack {
  8. public:
  9. SeqStack() : top(-1) {} // 构造函数,初始化栈顶为-1
  10. DataType data[StackSize];
  11. int top;
  12. void Push(DataType x);
  13. DataType pop();
  14. int Empty();
  15. void GenerateAndPushRandomNumbers(); // 生成随机数并压入栈
  16. void PopAndDisplay(int n); // 出栈并显示n个元素
  17. void DisplayTop(); // 显示栈顶元素
  18. };
  19. template <typename DataType>
  20. void SeqStack<DataType>::Push(DataType x) {
  21. if (top == StackSize - 1) throw "Overflow";
  22. data[++top] = x;
  23. }
  24. template <typename DataType>
  25. DataType SeqStack<DataType>::pop() {
  26. if (top == -1) throw "下溢";
  27. return data[top--];
  28. }
  29. template <typename DataType>
  30. int SeqStack<DataType>::Empty() {
  31. return top == -1;
  32. }
  33. template <typename DataType>
  34. void SeqStack<DataType>::GenerateAndPushRandomNumbers() {
  35. srand(time(nullptr)); // 初始化随机数种子
  36. for (int i = 0; i < 10; ++i) {
  37. int randomNumber = rand() % 100; // 生成0到99的随机数
  38. Push(randomNumber);
  39. }
  40. }
  41. template <typename DataType>
  42. void SeqStack<DataType>::PopAndDisplay(int n) {
  43. for (int i = 0; i < n; ++i) {
  44. DataType poppedElement = pop();
  45. cout << "Popped element: " << poppedElement << endl;
  46. }
  47. }
  48. template <typename DataType>
  49. void SeqStack<DataType>::DisplayTop() {
  50. if (!Empty()) {
  51. cout << "Top element: " << data[top] << endl;
  52. }
  53. else {
  54. cout << "Stack is empty." << endl;
  55. }
  56. }
  57. int main() {
  58. SeqStack<int> stack;
  59. stack.GenerateAndPushRandomNumbers(); // 生成随机数并压入栈
  60. // 显示栈内元素
  61. cout << "Elements in the stack (from top to bottom):";
  62. for (int i = stack.top; i >= 0; --i) {
  63. cout << " " << stack.data[i];
  64. }
  65. cout << endl;
  66. int n;
  67. cout << "Enter the number of elements to pop (1-10): ";
  68. cin >> n;
  69. stack.PopAndDisplay(n); // 出栈并显示元素
  70. stack.DisplayTop(); // 显示栈顶元素
  71. return 0;
  72. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/443656
推荐阅读
相关标签
  

闽ICP备14008679号