当前位置:   article > 正文

C++实现进栈、出栈_c++进栈出栈程序

c++进栈出栈程序

一、栈的定义

  1. class Stack
  2. {
  3. public:
  4. Stack(int len)
  5. {
  6. this->m_Array = new int[len] {};//初始化的数为0
  7. this->m_Idx = -1;
  8. this->m_Len = len;
  9. }
  10. void Push(int data);
  11. void Pop();
  12. void Print();
  13. ~Stack()
  14. {
  15. if (this->m_Array != nullptr)
  16. {
  17. delete[] this->m_Array;
  18. this->m_Array = nullptr;
  19. }
  20. }
  21. private:
  22. int m_Idx;
  23. int* m_Array;
  24. int m_Len;
  25. };

二、进栈

  1. void Stack::Push(int data)
  2. {
  3. if (this->m_Idx == this->m_Len - 1)
  4. {
  5. cout << "栈已满无法插入" << endl;
  6. }
  7. ++this->m_Idx;
  8. this->m_Array[this->m_Idx] = data;
  9. }

三、出栈

  1. void Stack::Pop()
  2. {
  3. if (this->m_Idx == -1)
  4. {
  5. cout << "栈为空栈,删除发生错误" << endl;
  6. }
  7. this->m_Array[this->m_Idx] = 0;//这里我是将其变成初始化的值来表示出栈
  8. --this->m_Idx;
  9. }

四、整体展示

  1. #include <iostream>
  2. using namespace std;
  3. class Stack
  4. {
  5. public:
  6. Stack(int len)
  7. {
  8. this->m_Array = new int[len] {};//初始化的数为0
  9. this->m_Idx = -1;
  10. this->m_Len = len;
  11. }
  12. void Push(int data);
  13. void Pop();
  14. void Print();
  15. ~Stack()
  16. {
  17. if (this->m_Array != nullptr)
  18. {
  19. delete[] this->m_Array;
  20. this->m_Array = nullptr;
  21. }
  22. }
  23. private:
  24. int m_Idx;
  25. int* m_Array;
  26. int m_Len;
  27. };
  28. void Stack::Push(int data)
  29. {
  30. if (this->m_Idx == this->m_Len - 1)
  31. {
  32. cout << "栈已满无法插入" << endl;
  33. }
  34. ++this->m_Idx;
  35. this->m_Array[this->m_Idx] = data;
  36. }
  37. void Stack::Pop()
  38. {
  39. if (this->m_Idx == -1)
  40. {
  41. cout << "栈为空栈,删除发生错误" << endl;
  42. }
  43. this->m_Array[this->m_Idx] = 0;//这里我是将其变成初始化的值来表示出栈
  44. --this->m_Idx;
  45. }
  46. void Stack::Print()
  47. {
  48. for (int i = 0; i <= this->m_Len - 1; ++i)
  49. {
  50. cout << this->m_Array[i] << " ";
  51. }
  52. cout << endl;
  53. }
  54. void Text()
  55. {
  56. Stack s(10);
  57. s.Push(1);
  58. s.Push(2);
  59. s.Push(3);
  60. s.Push(4);
  61. s.Push(5);
  62. s.Push(6);
  63. s.Print();
  64. s.Pop();
  65. s.Print();
  66. }
  67. int main()
  68. {
  69. Text();
  70. system("pause");
  71. return 0;
  72. }

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

闽ICP备14008679号