/* * MyArrayStack.h * * Created on: 2011-11-23 * Author: morin */ #ifndef MYArrayStack_H_ #define MYArrayStack_H_ #include "array.h" #include "utils.h" namespace ods { template class DualArrayDeque; template class MyArrayStack { protected: friend class DualArrayDeque; array a; int n; virtual void resize(); public: MyArrayStack(); virtual ~MyArrayStack(); int size(); T get(int i); T set(int i, T x); virtual void add(int i, T x); virtual void addAll(int i, MyArrayStack& x); virtual void add(T x) { add(size(), x); } virtual T remove(int i); virtual void clear(); }; template inline int MyArrayStack::size() { return n; } template inline T MyArrayStack::get(int i) { return a[i]; } template inline T MyArrayStack::set(int i, T x) { T y = a[i]; a[i] = x; return y; } template void MyArrayStack::clear() { n = 0; array b(1); a.swap(b); } template MyArrayStack::MyArrayStack() : a(1) { n = 0; } template MyArrayStack::~MyArrayStack() { } template void MyArrayStack::resize() { array b(max(2 * n, 1)); for (int i = 0; i < n; i++) b[i] = a[i]; a.swap(b); } template void MyArrayStack::add(int i, T x) { if (n + 1 > a.length) resize(); for (int j = n; j > i; j--) a[j] = a[j - 1]; a[i] = x; n++; } template void MyArrayStack::addAll(int i, MyArrayStack& x) { for (int j = 0; j < x.size(); j++){ add(i + j, x.get(j)); } } template T MyArrayStack::remove(int i) { T x = a[i]; for (int j = i; j < n - 1; j++) a[j] = a[j + 1]; n--; if (a.length >= 3 * n) resize(); return x; } } /* namespace ods */ #endif /* MyArrayStack_H_ */