Advertisement
CyberN00b

stack by dynamic arrays

Dec 10th, 2022 (edited)
889
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. template <typename T>
  5. struct my_stack{
  6. public:
  7.  
  8.     void push(T value) {
  9.         if (stack_size == data_size) {
  10.             resize();
  11.         }
  12.         data[stack_size++] = value;
  13.     }
  14.  
  15.     void pop() {
  16.         if (stack_size > 0)
  17.             --stack_size;
  18.     }
  19.  
  20.     T top() {
  21.         if (stack_size == 0)
  22.             throw out_of_range("stack is empty");
  23.         return data[stack_size - 1];
  24.     }
  25.  
  26.     size_t size() {
  27.         return stack_size;
  28.     }
  29.  
  30.     bool empty() {
  31.         return stack_size == 0;
  32.     }
  33.  
  34.     void clear() {
  35.         stack_size = 0;
  36.         data_size = 1;
  37.         delete [] data;
  38.         data = new T[data_size];
  39.     }
  40.  
  41.     void change_reserve_size(size_t reserve_size) {
  42.         if (stack_size >= reserve_size)
  43.             throw length_error("reserve size is smaller then stack size");
  44.         resize(reserve_size);
  45.     }
  46.  
  47.     ~my_stack() {
  48.         delete [] data;
  49.     }
  50.  
  51.     my_stack() : data(new T[data_size]) {}
  52.  
  53.     explicit my_stack(size_t reserve_size) : data(new T[reserve_size]), data_size(reserve_size) {}
  54.  
  55. private:
  56.  
  57.     size_t data_size = 1;
  58.     size_t stack_size = 0;
  59.     T* data;
  60.  
  61.     void resize(size_t new_size) {
  62.         T* new_data = new T[new_size];
  63.         memcpy(new_data, data, stack_size * sizeof(T));
  64.         data_size = new_size;
  65.         delete [] data;
  66.         data = new_data;
  67.     }
  68.    
  69.     void resize() {
  70.         resize(data_size * 2);
  71.     }
  72. };
  73.  
  74. int main() {
  75.     my_stack<int> s(100);
  76.     int a;
  77.     cin >> a;
  78.     for (int i = 0; i < a; ++i) {
  79.         int t;
  80.         cin >> t;
  81.         if (t == 0) {
  82.             int b;
  83.             cin >> b;
  84.             s.push(b);
  85.         } else if (t == 1) {
  86.             cout << s.top() << endl;
  87.         } else if (t == 2) {
  88.             cout << s.size() << endl;
  89.         } else if (t == 3) {
  90.             s.pop();
  91.         }
  92.     }
  93.     return 0;
  94. }
  95.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement