Advertisement
Guest User

Untitled

a guest
Feb 17th, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct iStack
  6. {
  7.     int capacity;
  8.     int top;
  9.     int* data;
  10.  
  11.     void init(int capacity);
  12.     void destroy();
  13.     void push(int value);
  14.     bool pop(int*);
  15. };
  16. bool iStack::pop(int* value)
  17. {
  18.     if (this->data != nullptr && this->top >= 0)
  19.     {
  20.         *value = this->data[this->top--];
  21.         return true;
  22.     }
  23.  
  24.     cout << "Something went wrong!" << endl;
  25.     return false;
  26.  
  27. }
  28.  
  29. void iStack::push(int value)
  30. {
  31.     if (this->data != nullptr && this->top < this->capacity - 1)
  32.     {
  33.         this->data[++(this->top)] = value;
  34.         return;
  35.     }
  36.  
  37.         cout << "Error pushin value!";
  38.     return;
  39. }
  40.  
  41. void iStack::init(int capacity)
  42. {
  43.     this->capacity = capacity;
  44.     this->top = -1;
  45.     this->data = new int[capacity];
  46. }
  47.  
  48. void iStack::destroy()
  49. {
  50.     delete[] this->data;
  51.     this->data = nullptr;
  52.     this->capacity = 0;
  53.     this->top = -1;
  54. }
  55.  
  56. int main()
  57. {
  58.     iStack stack;
  59.  
  60.     stack.init(3);
  61.  
  62.     stack.push(20);
  63.     stack.push(30);
  64.     stack.push(40);
  65.  
  66.     int value;
  67.  
  68.     stack.pop(&value);
  69.     cout << value << endl;
  70.  
  71.     stack.pop(&value);
  72.     cout << value << endl;
  73.  
  74.     stack.pop(&value);
  75.     cout << value << endl;
  76.  
  77.  
  78.     stack.destroy();
  79.  
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement