diff options
author | Santo Cariotti <dcariotti24@gmail.com> | 2020-05-10 18:45:36 +0200 |
---|---|---|
committer | Santo Cariotti <dcariotti24@gmail.com> | 2020-05-10 18:45:46 +0200 |
commit | 60d26b0811b4a821cac8ecbbfdf11f18322d83fa (patch) | |
tree | c48d1262775423ae2ad9423962fc939681a9c49e /I_anno | |
parent | 4527eda2f32a3d200b03aee03ea108aa49262589 (diff) |
feat: queue data structure
Diffstat (limited to 'I_anno')
-rw-r--r-- | I_anno/Programmazione_2/data_structures/queue.cc | 74 |
1 files changed, 74 insertions, 0 deletions
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<iostream> + +using namespace std; + +template<typename T> +struct node { + T value; + node<T>* next; +}; + +template<class T> +class queue { +public: + queue() : _head{nullptr} {} + ~queue() { + auto iter = _head; + while(iter) { + delete iter; + iter = iter->next; + } + } + queue<T>* enqueue(T val) { + + if(!_head) { + _head = new node<T>{val, nullptr}; + _tail = _head; + } else { + _tail->next = new node<T>{val, nullptr}; + _tail = _tail->next; + } + + return this; + } + + queue<T>* 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<T>* _tail; + node<T>* _head; +}; + +int main() { + queue<int>* q = new queue<int>(); + + q->dequeue(); + q->enqueue(4)->enqueue(2)->enqueue(8); + q->dequeue(); + q->enqueue(1); + q->print(); + + delete q; + return 0; +} |