From 60d26b0811b4a821cac8ecbbfdf11f18322d83fa Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Sun, 10 May 2020 18:45:36 +0200 Subject: feat: queue data structure --- I_anno/Programmazione_2/data_structures/queue.cc | 74 ++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 I_anno/Programmazione_2/data_structures/queue.cc (limited to 'I_anno/Programmazione_2/data_structures') diff --git a/I_anno/Programmazione_2/data_structures/queue.cc b/I_anno/Programmazione_2/data_structures/queue.cc new file mode 100644 index 0000000..476074f --- /dev/null +++ b/I_anno/Programmazione_2/data_structures/queue.cc @@ -0,0 +1,74 @@ +#include + +using namespace std; + +template +struct node { + T value; + node* next; +}; + +template +class queue { +public: + queue() : _head{nullptr} {} + ~queue() { + auto iter = _head; + while(iter) { + delete iter; + iter = iter->next; + } + } + queue* enqueue(T val) { + + if(!_head) { + _head = new node{val, nullptr}; + _tail = _head; + } else { + _tail->next = new node{val, nullptr}; + _tail = _tail->next; + } + + return this; + } + + queue* dequeue() { + auto iter = _head; + + if(!_head) return this; + while(iter->next != _tail) { + iter = iter->next; + } + + delete iter->next; + iter->next = nullptr; + _tail = iter; + + return this; + } + + void print() { + auto iter = _head; + while(iter) { + cout << iter->value << ' '; + iter = iter->next; + } + cout << endl; + } +private: + node* _tail; + node* _head; +}; + +int main() { + queue* q = new queue(); + + q->dequeue(); + q->enqueue(4)->enqueue(2)->enqueue(8); + q->dequeue(); + q->enqueue(1); + q->print(); + + delete q; + return 0; +} -- cgit v1.2.3-18-g5258