Advertisement
Mary_99

task 1b full do oddania

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