Advertisement
Guest User

task2b

a guest
Oct 22nd, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1.  
  2. #include <stdlib.h>
  3. #include <iostream>
  4. #include "stack.h"
  5.  
  6. using namespace std;
  7.  
  8. stack::stack()
  9. {
  10.   //  this->top=0;
  11.     this->data = (int*)malloc(sizeof(int) * 2);
  12.     if(this->data == NULL)
  13.     {
  14.         cout << "unable to allocate memory" << endl;
  15.         exit(1);
  16.     }
  17.     this->top=-1;
  18.     this->size=2;
  19. }
  20. stack::~stack()
  21. {
  22.     free(this-> data);
  23. }
  24.  
  25. bool stack::isEmpty()
  26. {
  27.     if(this->top == -1)
  28.     {
  29.         return true;
  30.     }
  31.     else
  32.     {
  33.         return false;
  34.     }
  35. }
  36.  
  37. void stack::push(int element)
  38. {
  39.     int *temp = (int*)malloc(sizeof(int) * this->size * 2);
  40.         if (temp == NULL)
  41.         {
  42.             cout <<"unable to allocate" << endl;
  43.             return;
  44.         }
  45.         int i=0;
  46.         for(i = 0; i<= this ->top; i++)
  47.         {
  48.             temp[i] = this->data[i];
  49.         }
  50.         free(this->data);
  51.         this->data = temp;
  52.         this-> size *=2;
  53.     this-> data[++this->top] = element;
  54. }
  55.  
  56. int stack::pop()
  57. {
  58.     if(isEmpty())
  59.     {
  60.         cout << "stack is empty" << endl;
  61.         free(this->data);
  62.         exit(-1);
  63.     }
  64.     else
  65.     {
  66.         return this->data[this->top--];
  67.     }
  68. }
  69.  
  70. stack::stack(const stack &s)
  71. {
  72.     this->data = (int*)malloc(sizeof(int) * s.size);
  73.     if(this->data == NULL)
  74.     {
  75.         printf("unable to allocate memory");
  76.         exit(1);
  77.     }
  78.     this->top=s.top;
  79.     this->size=s.size;
  80.     for(int i = this->top; i>=0;i--)
  81.     {
  82.         this->data[i] = s.data[i];
  83.     }
  84. }
  85.  
  86.  
  87. stack & stack::operator= (const stack & s)
  88. {
  89.   if(this->size != s.size)
  90.     {
  91.         this->data = (int*)realloc(this->data, sizeof(int) * (s.size));
  92.     }
  93.    
  94.     this->top=s.top;
  95.     this->size=s.size;
  96.     for(int i = s.top; i>=0;i--)
  97.     {
  98.         this->data[i] = s.data[i];
  99.     }
  100.     return *this;
  101. }
  102. void stack::display()
  103. {
  104.       for(int i =this->top; i>=0; i--)
  105.     {
  106.         printf(" %d ", this->data[i]);
  107.     }
  108.     printf("\n");
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement