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/Queue/Queue_Dynamic.hpp | 60 ++++++++++++++++++++++ .../HomeworkExamPrep/Queue/Queue_Static.hpp | 37 +++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 Year 2/Structures and data algorithms/HomeworkExamPrep/Queue/Queue_Dynamic.hpp create mode 100644 Year 2/Structures and data algorithms/HomeworkExamPrep/Queue/Queue_Static.hpp (limited to 'Year 2/Structures and data algorithms/HomeworkExamPrep/Queue') diff --git a/Year 2/Structures and data algorithms/HomeworkExamPrep/Queue/Queue_Dynamic.hpp b/Year 2/Structures and data algorithms/HomeworkExamPrep/Queue/Queue_Dynamic.hpp new file mode 100644 index 0000000..02c8888 --- /dev/null +++ b/Year 2/Structures and data algorithms/HomeworkExamPrep/Queue/Queue_Dynamic.hpp @@ -0,0 +1,60 @@ +#ifndef QUEUE_DYNAMIC +#define QUEUE_DYNAMIC + +template +class Queue { + struct Node { + T val; + Node* next; + + Node(const T& v) : val(v), next(nullptr) {} + }; + + Node* head; + Node* tail; + +public: + Queue(); + ~Queue(); + Queue(Queue& other) = delete; + Queue& operator=(Queue& other) = delete; + + void push(const T& v); + void pop(); + T& front(); +}; + +template +Queue::Queue() : head(nullptr), tail(nullptr) {} + +template +Queue::~Queue() { + while (head != nullptr) + pop(); +} + +template +void Queue::push(const T& v) { + if (head == nullptr) { + head = tail = new Node(v); + } + else { + tail->next = new Node(v); + tail = tail->next; + } +} + +template +void Queue::pop() { + Node* toDel = head; + head = head->next; + delete toDel; + if (head == nullptr) tail = nullptr; +} + +template +T& Queue::front() { + return head->val; +} + +#endif diff --git a/Year 2/Structures and data algorithms/HomeworkExamPrep/Queue/Queue_Static.hpp b/Year 2/Structures and data algorithms/HomeworkExamPrep/Queue/Queue_Static.hpp new file mode 100644 index 0000000..2b9dc8d --- /dev/null +++ b/Year 2/Structures and data algorithms/HomeworkExamPrep/Queue/Queue_Static.hpp @@ -0,0 +1,37 @@ +#ifndef QUEUE_STATIC +#define QUEUE_STATIC + +#include +#define QUEUE_SIZE 1024 + +template +class Queue { + T vals[QUEUE_SIZE]; + unsigned frontInd; + unsigned backInd; + +public: + void push(const T& v); + void pop(); + T& front(); +}; + +template +void Queue::push(const T& v) { + vals[backInd++ % QUEUE_SIZE] = v; + + if (backInd == frontInd) + throw std::logic_error("Queue overfill!"); +} + +template +void Queue::pop() { + frontInd++; +} + +template +T& Queue::front() { + return vals[frontInd]; +} + +#endif -- cgit v1.3.1-26-gb76a