From b0e77499f3a87539dc2f1d9f64f7448d7c0914fc Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Thu, 14 May 2020 15:09:43 +0200 Subject: fix: research for list double linked It uses prev pointer instead of a new linear search --- .../data_structures/list_double.cc | 30 ++++++++++++---------- 1 file changed, 16 insertions(+), 14 deletions(-) (limited to 'I_anno/Programmazione_2/data_structures/list_double.cc') diff --git a/I_anno/Programmazione_2/data_structures/list_double.cc b/I_anno/Programmazione_2/data_structures/list_double.cc index 79cd8c3..fa0af26 100644 --- a/I_anno/Programmazione_2/data_structures/list_double.cc +++ b/I_anno/Programmazione_2/data_structures/list_double.cc @@ -24,7 +24,7 @@ public: } list* push_front(T val) { - if(_head == nullptr) { + if(!_head) { _head = new node{val, nullptr, nullptr}; } else { _head = new node{val, nullptr, _head}; @@ -80,12 +80,9 @@ public: node* elem = _search(val); if(!elem) return this; - node* iter = _head; - if(iter == elem) return this->pop_front(); - - while(iter->next != elem) - iter = iter->next; + if(elem == _head) return this->pop_front(); + node* iter = elem->prev; node* temp = iter->next; iter->next = iter->next->next; iter->next->prev = iter; @@ -95,7 +92,7 @@ public: } list* pop_front() { - if(_head == nullptr) + if(!_head) return this; node* elem = _head; @@ -107,14 +104,10 @@ public: } list* pop_back() { - if(_head == nullptr) + if(!_head) return this; - node* iter = _head; - - while(iter->next && iter->next->next) { - iter = iter->next; - } + node* iter = _last()->prev; if(iter->next == nullptr) { delete iter; @@ -132,7 +125,7 @@ public: void print() { node* iter = _head; - while(iter != nullptr) { + while(iter) { cout << iter->value << ' '; cout << "[[ " << (iter->prev!=nullptr ? iter->prev->value : -1) << ", "; cout << (iter->next!=nullptr ? iter->next->value : -1) << " ]], "; @@ -140,6 +133,15 @@ public: } } private: + node* _last() { + node* iter = _head; + while(iter->next) { + iter = iter->next; + } + + return iter; + } + node* _search(T value) { node* iter = _head; while(iter && iter->value != value) -- cgit v1.2.3-18-g5258