From f7a2745ec3198d3da55e5ea8131192638bce5a38 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Sat, 2 May 2020 19:49:18 +0200 Subject: feat: singular list --- I_anno/Programmazione_2/data_structures/list.cc | 105 ++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 I_anno/Programmazione_2/data_structures/list.cc (limited to 'I_anno/Programmazione_2') diff --git a/I_anno/Programmazione_2/data_structures/list.cc b/I_anno/Programmazione_2/data_structures/list.cc new file mode 100644 index 0000000..c0915e7 --- /dev/null +++ b/I_anno/Programmazione_2/data_structures/list.cc @@ -0,0 +1,105 @@ +#include + +using namespace std; + +template +struct node { + T value; + node* next; +}; + + +template +class list { +public: + list() : _head{nullptr} {} + + ~list() { + while(_head != nullptr) { + node* tmp = _head->next; + delete tmp; + _head = tmp; + } + } + + list* push_front(T val) { + _head = new node{val, _head}; + + return this; + } + + list* push_back(T val) { + node* iter = _head; + if(_head == nullptr) { + _head = new node{val, nullptr}; + } else { + while(iter->next != nullptr) { + iter = iter->next; + } + iter->next = new node{val, nullptr}; + } + + return this; + } + + list* push_after_value(T val, T newval) { + node* iter = _head; + while(iter && iter->value != val) + iter = iter->next; + + if(iter == nullptr) + return this->push_front(newval); + + iter->next = new node{newval, iter->next}; + + return this; + } + + list* push_before_value(T val, T newval) { + node* iter = _head; + + while(iter && iter->next && iter->next->value != val) + iter = iter->next; + + if(iter == nullptr) + return this->push_front(newval); + + iter->next = new node{newval, iter->next}; + + return this; + } + + void print() { + node* iter = _head; + while(iter != nullptr) { + cout << iter->value << ' '; + iter = iter->next; + } + } +private: + node* _head; +}; + +int main() { + list* l = new list{}; + l->push_front(2)->push_front(1.7); + // 1.7 2 + + l->push_back(5.2); + // 2 1.7 5.2 + + l->push_back(10.1)->push_back(15); + // 2 1.7 5.2 10.1 15 + + l->push_after_value(5.2, 6.4); + // 2 1.7 5.2 6.4 10.1 15 + + l->push_before_value(5.2, 4.1); + // 2 1.7 4.1 5.2 6.4 10.1 15 + + l->push_before_value(4.1, 3.0); + // 2 1.7 3.0 4.1 5.2 6.4 10.1 15 + l->print(); + + return 0; +} -- cgit v1.2.3-18-g5258