diff options
suggest changes
In the remove_after function, I added a check if (!it.currentElementPtr->next) because if we have a list with two elements and move an iterator to the end of the list, it will try to access to_delete->next, which would result in an error. This check also handles the case when the size is equal to 1. In the insert_after function, if we insert after the tail and then try to push_back another element, we might lose data. Therefore, if itNode == _tail, we should update _tail to point to the new node.
1 files changed, 7 insertions, 3 deletions
| -rw-r--r-- | Seminar05/src/singly-linked-list/singly-linked-list.hpp | 10 |
diff --git a/Seminar05/src/singly-linked-list/singly-linked-list.hpp b/Seminar05/src/singly-linked-list/singly-linked-list.hpp index 3ad895e..d8b73db 100644 --- a/Seminar05/src/singly-linked-list/singly-linked-list.hpp +++ b/Seminar05/src/singly-linked-list/singly-linked-list.hpp @@ -152,7 +152,7 @@ public: }; - const_sll_iterator begin() + sll_iterator begin() { return sll_iterator(_head); } @@ -298,6 +298,10 @@ typename singly_linked_list<T>::sll_iterator singly_linked_list<T>::insert_after new_node->next = itNode->next; itNode->next = new_node; _size++; + if(itNode == _tail){ + _tail = new_node; + } + return singly_linked_list<T>::sll_iterator(new_node); } @@ -305,7 +309,7 @@ typename singly_linked_list<T>::sll_iterator singly_linked_list<T>::insert_after template <typename T> typename singly_linked_list<T>::sll_iterator singly_linked_list<T>::remove_after(const typename singly_linked_list<T>::const_sll_iterator& it) { - if(it == end() || size() == 1) + if(it == end() || !it.currentElementPtr->next) return end(); node* to_delete = (it + 1).currentElementPtr; @@ -415,4 +419,4 @@ void singly_linked_list<T>::free() } _head = _tail = nullptr; _size = 0; -}
\ No newline at end of file +} |
