fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5.  
  6. class DynamicIntegerStack
  7. {
  8. private:
  9. int *bottom_;
  10. int *top_;
  11. int size_;
  12. public:
  13. DynamicIntegerStack(int n = 20){
  14. bottom_ = new int[n];
  15. top_ = bottom_;
  16. size_ = n;
  17. }
  18.  
  19. int getSize(){ return size_; }
  20.  
  21. void push(int c){
  22. if (!full()){
  23. *top_ = c;
  24. top_++;
  25. }
  26. else{
  27. resize(size_ * 2);
  28. *top_ = c;
  29. top_++;
  30. }
  31. }
  32.  
  33. void resize(int newSize){
  34. //Allocate new array and copy in data
  35. int *newArray = new int[newSize];
  36. std::copy(bottom_, bottom_+size_, newArray);
  37.  
  38. // Set the top to the new array
  39. top_ = newArray + (top_ - bottom_);
  40.  
  41. // Delete old array
  42. delete[] bottom_;
  43.  
  44. // Update pointers and size
  45. bottom_ = newArray;
  46. size_ = newSize;
  47.  
  48. cout << "array has been resized" << endl;
  49. }
  50.  
  51. int num_items() {
  52. return (top_ - bottom_);
  53. }
  54. char pop(){
  55. top_--;
  56. return *top_;
  57. }
  58. int full() {
  59. return (num_items() >= size_);
  60. }
  61. int empty() {
  62. return (num_items() <= 0);
  63. }
  64. void print(){
  65. cout << "Stack currently holds " << num_items() << " items: ";
  66. for (int *element = bottom_; element<top_; element++) {
  67. cout << " " << *element;
  68. }
  69. cout << "\n";
  70. }
  71. ~DynamicIntegerStack(){ // stacks when exiting functions
  72. delete[] bottom_;
  73. }
  74. };
  75.  
  76.  
  77. int main(){
  78. DynamicIntegerStack s(5);
  79. s.print(); cout << "\n";
  80. s.push(1); s.push(3); s.push(5); s.push(10); s.push(15);
  81. s.print(); cout << "\n";
  82. s.push(20);
  83. s.print(); cout << "\n";
  84. cout << "Popped value is: " << s.pop() << "\n";
  85. s.print(); cout << "\n";
  86. s.push(30);
  87. s.print(); cout << "\n";
  88. s.pop();
  89. s.pop();
  90. s.print(); cout << "\n";
  91. while (!s.empty()) s.pop();
  92. if (s.num_items() != 0) {
  93. cout << "Error: Stack is corrupt!\n";
  94. }
  95. s.print(); cout << "\n";
  96. // destructor for s automatically called
  97. return 0;
  98. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
Stack currently holds 0 items: 

Stack currently holds 5 items:  1 3 5 10 15

array has been resized
Stack currently holds 6 items:  1 3 5 10 15 20

Popped value is: 
Stack currently holds 5 items:  1 3 5 10 15

Stack currently holds 6 items:  1 3 5 10 15 30

Stack currently holds 4 items:  1 3 5 10

Stack currently holds 0 items: