fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. class Stack
  7. {
  8. private:
  9. int* arr;
  10. int cap;
  11. int topIdx;
  12. public:
  13. Stack(int c = 100);
  14. ~Stack();
  15. void push(int value);
  16. void pop();
  17. int top();
  18. bool isEmpty();
  19. int size();
  20. };
  21.  
  22. Stack::Stack(int c) : cap(c), topIdx(-1)
  23. {
  24. arr = new int[cap];
  25. }
  26.  
  27. Stack::~Stack()
  28. {
  29. if (arr)
  30. {
  31. delete[] arr;
  32. arr = nullptr;
  33. }
  34. }
  35.  
  36. void Stack::push(int value)
  37. {
  38. if (topIdx + 1 == cap)
  39. {
  40. cout << "Stack is overflow\n";
  41. return;
  42. }
  43.  
  44. arr[++topIdx] = value;
  45. }
  46.  
  47. void Stack::pop()
  48. {
  49. if (!isEmpty())
  50. {
  51. topIdx--;
  52. }
  53. else
  54. {
  55. cout << "Stack is empty\n";
  56. }
  57. }
  58.  
  59. int Stack::top()
  60. {
  61. if (!isEmpty())
  62. {
  63. return arr[topIdx];
  64. }
  65. else
  66. {
  67. cout << "Stack is empty\n";
  68. return -1;
  69. }
  70. }
  71.  
  72. bool Stack::isEmpty()
  73. {
  74. return topIdx == -1;
  75. }
  76.  
  77. int Stack::size()
  78. {
  79. return topIdx + 1;
  80. }
  81.  
  82. int main() {
  83. Stack s;
  84. s.push(10);
  85. s.push(20);
  86. s.push(30);
  87.  
  88. cout << "Top element: " << s.top() << "\n";
  89. s.pop();
  90. cout << "Top element after pop: " << s.top() << "\n";
  91. cout << "Stack size: " << s.size() << "\n";
  92.  
  93. return 0;
  94. }
  95.  
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
Top element: 30
Top element after pop: 20
Stack size: 2