diff options
[SDP/HEP] Added preparation for "homework" during class
1 files changed, 62 insertions, 0 deletions
| -rw-r--r-- | Year 2/Structures and data algorithms/HomeworkExamPrep/Stack/Stack_DynamicSeq.hpp | 62 |
diff --git a/Year 2/Structures and data algorithms/HomeworkExamPrep/Stack/Stack_DynamicSeq.hpp b/Year 2/Structures and data algorithms/HomeworkExamPrep/Stack/Stack_DynamicSeq.hpp new file mode 100644 index 0000000..7f794e7 --- /dev/null +++ b/Year 2/Structures and data algorithms/HomeworkExamPrep/Stack/Stack_DynamicSeq.hpp @@ -0,0 +1,62 @@ +#ifndef STACK_DYNAMIC +#define STACK_DYNAMIC + +template <class T> +class Stack { + T* vals; + unsigned topInd; + unsigned size; + + void resize(); + +public: + Stack(); + ~Stack(); + Stack(Stack& other) = delete; + Stack& operator=(const Stack& other) = delete; + + void push(const T& v); + void pop(); + T& top(); +}; + +template <class T> +void Stack<T>::resize() { + unsigned newSize = size << 1; + T* newVals = new T[newSize]; + for (unsigned i = 0; i < size; i++) + newVals[i] = vals[i]; + delete vals; + vals = newVals; + size = newSize; +} + +template <class T> +Stack<T>::Stack() { + vals = new T[1]; // for testing purposes its 1 +} + +template <class T> +Stack<T>::~Stack() { + delete[] vals; +} + +template <class T> +void Stack<T>::push(const T& v) { + if (topInd == size) + resize(); + + vals[topInd++] = v; +} + +template <class T> +void Stack<T>::pop() { + topInd--; +} + +template <class T> +T& Stack<T>::top() { + return vals[topInd - 1]; +} + +#endif |
