summaryrefslogtreecommitdiff
path: root/Year_1/Programming_2/data_structures/queue_w_array.cc
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2021-02-06 19:56:36 +0100
committerSanto Cariotti <santo@dcariotti.me>2021-02-06 19:56:36 +0100
commitd2edbc38cac8da52f58c5cd3da6c0c625fa05736 (patch)
treea51e9a4e56fc9d4c7c9e37576dceedca3a0c72b4 /Year_1/Programming_2/data_structures/queue_w_array.cc
parent98f34040820dc3a964b7be59a698323e8cc6c8a3 (diff)
conf: rename
Diffstat (limited to 'Year_1/Programming_2/data_structures/queue_w_array.cc')
-rw-r--r--Year_1/Programming_2/data_structures/queue_w_array.cc66
1 files changed, 66 insertions, 0 deletions
diff --git a/Year_1/Programming_2/data_structures/queue_w_array.cc b/Year_1/Programming_2/data_structures/queue_w_array.cc
new file mode 100644
index 0000000..fb92d68
--- /dev/null
+++ b/Year_1/Programming_2/data_structures/queue_w_array.cc
@@ -0,0 +1,66 @@
+#include<iostream>
+
+using namespace std;
+
+template<class H>
+class queue {
+public:
+ queue(int n) : _size{n}, _counter{0}, _head{0}, _tail{0} {
+ _arr = new H[n];
+ }
+ ~queue() {
+ delete _arr;
+ }
+ bool is_empty() {
+ return _counter == 0;
+ }
+ bool is_full() {
+ return _counter == _size;
+ }
+
+ queue<H>* enqueue(H x) {
+ if(!is_full()) {
+ _arr[_tail] = x;
+ if(_tail == _size-1)
+ _tail = 0;
+ else
+ ++_tail;
+ _counter++;
+ }
+
+ return this;
+ }
+ H dequeue() {
+ if(is_empty()) return -1;
+ H x = _arr[_head];
+
+ if(_head == _size-1)
+ _head = 0;
+ else
+ ++_head;
+
+ _counter--;
+ return x;
+ }
+private:
+ H* _arr;
+ int _size;
+ short _counter;
+ short _head;
+ short _tail;
+};
+
+int main() {
+ queue<int>* q = new queue<int>{4};
+ q->enqueue(5)->enqueue(13)->enqueue(3);
+ cout << q->dequeue() << '\n';
+ q->enqueue(4)->enqueue(6)->enqueue(7);
+ q->dequeue();
+ q->enqueue(7);
+
+ for(int i = 0; i < 6; ++i) {
+ cout << q->dequeue() << ' ';
+ }
+ delete q;
+ return 0;
+}