fork download
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. using namespace std;
  5.  
  6. class AStack {
  7. public:
  8. AStack(int size=25);
  9. AStack(const AStack&);
  10. ~AStack();
  11. AStack& operator = (AStack s);
  12. void push(int);
  13. int pop();
  14. int top();
  15. bool isEmpty();
  16. void flush();
  17.  
  18. private:
  19. int capacity ;
  20. int* a;
  21. int index; // Index of the top most element
  22. };
  23.  
  24.  
  25. AStack::AStack(int size) : index(-1), a(new int[size]()), capacity(size) {}
  26.  
  27. AStack::AStack(const AStack& s) : capacity(s.capacity), a(new int[capacity]()), index(s.index)
  28. { std::copy(s.a, s.a + capacity, a); }
  29.  
  30. AStack::~AStack()
  31. { delete[] a; }
  32.  
  33. AStack& AStack::operator = (AStack s)
  34. {
  35. std::swap(capacity, s.capacity);
  36. std::swap(a, s.a);
  37. std::swap(index, s.index);
  38. return *this;
  39. }
  40.  
  41. void AStack::push(int x) {
  42. if (index == capacity - 1) {
  43. cout << "\n\nThe stack is full. Couldn't insert " << x << "\n\n";
  44. return;
  45. }
  46. a[++index] = x;
  47. }
  48.  
  49. int AStack::pop() {
  50. if (index == -1) {
  51. cout << "\n\nNo elements to pop\n\n";
  52. return -1;
  53. }
  54. return a[index--];
  55. }
  56.  
  57. int AStack::top() {
  58. if (index == -1) {
  59. cout << "\n\nNo elements in the Stack\n\n";
  60. return -1;
  61. }
  62. return a[index];
  63. }
  64.  
  65. bool AStack::isEmpty() {
  66. return (index == -1);
  67. }
  68.  
  69. void AStack::flush() {
  70. if (index == -1) {
  71. cout << "\n\nNo elements in the Stack to flush\n\n";
  72. return;
  73. }
  74. cout << "\n\nFlushing the Stack: ";
  75. while (index != -1) {
  76. cout << a[index--] << " ";
  77. }
  78. cout << endl << endl;
  79. }
  80.  
  81. AStack& reverseStack(AStack& s1) {
  82. AStack s2;
  83. while (!s1.isEmpty()) {
  84. s2.push(s1.pop());
  85. }
  86. s1 = s2;
  87. return s1;
  88. }
  89.  
  90. int main() {
  91. AStack s1;
  92. s1.push(1);
  93. s1.push(2);
  94. s1.push(3);
  95. s1.push(4);
  96. s1.push(5);
  97. s1 = reverseStack(s1);
  98. cout << "\n\nFlushing s1:\n";
  99. s1.flush();
  100. return 0;
  101. }
  102.  
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout

Flushing s1:


Flushing the Stack:  1  2  3  4  5