Advertisement
Mary_99

1b CORRRECT

Oct 25th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <string.h>
  3. #include "Stack.h"
  4. #define STACKSIZE 3
  5. #define INIT -1
  6.  
  7. using namespace std;
  8.  
  9.  Stack::Stack()
  10. {
  11.     totalSize = STACKSIZE;
  12.     top = INIT;
  13.     array = (int*)malloc(sizeof(int)*totalSize);
  14.     if(array == NULL)
  15.     {
  16.         printf("Memory not allocated\n");
  17.         abort();
  18.     }
  19.  
  20. }
  21.  
  22. void Stack::push(int element)
  23. {
  24.     if(top == totalSize - 1)
  25.     {
  26.         totalSize *= 2;
  27.         int *temp = (int*)realloc(array, sizeof(int)*totalSize);
  28.         if(temp == NULL)
  29.         {
  30.            cout<<"Realloc failed"<<endl;
  31.             abort();
  32.         } else {
  33.             array = temp;
  34.         }
  35.     }
  36.     array[++top] = element;
  37. }
  38.  
  39. int Stack::pop()
  40. {
  41.     if(isEmpty())
  42.     {
  43.         cout<<"Stack is empty"<<endl;
  44.         abort();
  45.     }
  46.     return array[top--];
  47. }
  48.  
  49. bool Stack::isEmpty()
  50. {
  51.     if(top == -1)
  52.     {
  53.         return true;
  54.     } else {
  55.         return false;
  56.     }
  57. }
  58.  
  59. void Stack::getTotatSize()
  60. {
  61.     printf("Size of stack is: %d\n", totalSize);
  62. }
  63.  
  64. Stack::~Stack()
  65. {
  66.    free(array);
  67.  
  68. }
  69. #ifndef STACK_H
  70. #define STACK_H
  71.  
  72. class Stack{
  73.    
  74.     int totalSize;
  75.     int top;
  76.     int * array;
  77.    
  78.     public:
  79.     void push(int elemennt);
  80.     int pop();
  81.     bool isEmpty();
  82.     void getTotatSize();
  83.     Stack();
  84.     ~Stack();
  85.    
  86. };  
  87.  
  88. #endif
  89. #include <iostream>
  90. #include <string>
  91. #include <string.h>
  92. #include "Stack.h"
  93. #include "Stack.cpp"
  94.  
  95. #define STACKSIZE 3
  96.  
  97. using namespace std;
  98.  
  99.  
  100. int main(int argc, char const *argv[])
  101. {
  102.     Stack newStack;
  103.      
  104.     newStack.push(5);
  105.     newStack.push(3);
  106.     newStack.push(15);
  107.    
  108.     newStack.getTotatSize();
  109.  
  110.     newStack.push(35);
  111.     newStack.push(45);
  112.    
  113.     newStack.getTotatSize();
  114.  
  115.  
  116.     cout << newStack.pop() << endl;
  117.  
  118.     return 0;
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement