当前位置:   article > 正文

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

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

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

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

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

闽ICP备14008679号