From 9d9bd35065ded1d78c9a07af2953e69fc8eb61d4 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sun, 8 Jan 2023 22:35:13 +0200 Subject: [SDP/HEP] Added preparation for "homework" during class --- .../HomeworkExamPrep/Stack/Stack_DynamicSeq.hpp | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Year 2/Structures and data algorithms/HomeworkExamPrep/Stack/Stack_DynamicSeq.hpp (limited to 'Year 2/Structures and data algorithms/HomeworkExamPrep/Stack/Stack_DynamicSeq.hpp') 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 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 +void Stack::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 +Stack::Stack() { + vals = new T[1]; // for testing purposes its 1 +} + +template +Stack::~Stack() { + delete[] vals; +} + +template +void Stack::push(const T& v) { + if (topInd == size) + resize(); + + vals[topInd++] = v; +} + +template +void Stack::pop() { + topInd--; +} + +template +T& Stack::top() { + return vals[topInd - 1]; +} + +#endif -- cgit v1.3.1-23-gd82d