Advertisement
Mary_99

almost 1b

Oct 19th, 2019
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. #define STACKSIZE 20
  5.  
  6. using namespace std;
  7.  
  8. class Stack{
  9.    
  10.     int totalSize;
  11.     int top;
  12.     int * array;
  13.    
  14.     public:
  15.     void push(int a);
  16.     int pop();
  17.     Stack(int size);
  18.     ~Stack();
  19.     bool isEmpty();
  20.     bool isFull();
  21.    
  22. };      
  23.        
  24. Stack::Stack(int size){
  25.     this->totalSize = size;
  26.     this->top = 0;
  27.     this->array = new int[this->totalSize]; //create the dynamic array
  28. }
  29.  
  30. Stack::~Stack(){
  31.     free(this-> array);
  32. }
  33.        
  34. bool Stack:: isEmpty(){
  35.     return this->top == false;
  36.    
  37. }
  38. bool Stack:: isFull(){
  39.     return this->top == this->totalSize -1;//-1
  40. }
  41.  
  42.  
  43. void Stack::push(int element){
  44.     if(isFull()){
  45.         this->array = (int*)malloc(sizeof(int)* this->totalSize * 2);
  46.         this->totalSize *= 2;
  47.     } else{  
  48.         this->array[this->top] = element;
  49.         this->top++;
  50.         }
  51. }
  52.    
  53. int Stack:: pop(){
  54.     if(isEmpty()){
  55.         cout << "Stack is empty" << endl;
  56.         abort();
  57.     }
  58.     else{
  59.         this->top--;
  60.         return this->array[this->top];
  61.     }
  62. }
  63.  
  64.  
  65. int main(int argc, char const *argv[])
  66. {
  67.     Stack * newStack = new Stack(STACKSIZE);
  68.    
  69.     newStack->push(5);
  70.     newStack->push(3);
  71.     newStack->push(15);
  72.     newStack->push(35);
  73.     newStack->push(45);
  74.    
  75.     cout<< newStack->pop() << endl;
  76.     //cout <<"Size of the stack: ", newStack->totalSize << endl;
  77.  
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement