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