Extend LList (#20555)

This commit is contained in:
s-hadinger 2024-01-21 18:40:27 +01:00 committed by GitHub
parent 95f76d623f
commit 9006386cf2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 28 additions and 5 deletions

View File

@ -59,9 +59,9 @@ public:
~LList() { reset(); } ~LList() { reset(); }
// remove elements // remove elements
void removeHead(void); // remove first element T * removeHead(void); // remove first element
void reset(void); // remove all elements void reset(void); // remove all elements
void remove(const T * val); const T * remove(const T * val);
// read the list // read the list
inline bool isEmpty(void) const { return (_head == nullptr) ? true : false; } inline bool isEmpty(void) const { return (_head == nullptr) ? true : false; }
@ -77,6 +77,7 @@ public:
T & addHead(void); T & addHead(void);
T & addHead(const T &val); T & addHead(const T &val);
T & addToLast(void); T & addToLast(void);
T & insertAt(size_t index);
// add an element allocated externally // add an element allocated externally
// memory is free by us now -- don't free it! // memory is free by us now -- don't free it!
T & addHead(LList_elt<T> * elt); T & addHead(LList_elt<T> * elt);
@ -142,17 +143,21 @@ void LList<T>::reset(void) {
} }
template <typename T> template <typename T>
void LList<T>::removeHead(void) { T * LList<T>::removeHead(void) {
if (_head) { if (_head) {
T & orginal_head = _head.val;
LList_elt<T> * next = _head->next(); LList_elt<T> * next = _head->next();
delete _head; delete _head;
_head = next; _head = next;
return orginal_head;
} else {
return nullptr;
} }
} }
template <typename T> template <typename T>
void LList<T>::remove(const T * val) { const T * LList<T>::remove(const T * val) {
if (nullptr == val) { return; } if (nullptr == val) { return val; }
// find element in chain and find pointer before // find element in chain and find pointer before
LList_elt<T> **curr_ptr = &_head; LList_elt<T> **curr_ptr = &_head;
while (*curr_ptr) { while (*curr_ptr) {
@ -164,6 +169,7 @@ void LList<T>::remove(const T * val) {
} }
curr_ptr = &((*curr_ptr)->_next); // move to next element curr_ptr = &((*curr_ptr)->_next); // move to next element
} }
return val;
} }
template <typename T> template <typename T>
@ -201,6 +207,23 @@ T & LList<T>::addToLast(void) {
return elt->_val; return elt->_val;
} }
template <typename T>
T & LList<T>::insertAt(size_t index) {
LList_elt<T> **curr_ptr = &_head;
size_t count = 0;
while (*curr_ptr) {
if (count == index) {
LList_elt<T> * elt = new LList_elt<T>(); // create element
elt->next((*curr_ptr)->next());
(*curr_ptr)->next(elt);
return elt->_val;
}
curr_ptr = &((*curr_ptr)->_next);
count++;
}
return addToLast();
}
template <typename T> template <typename T>
T & LList<T>::addToLast(LList_elt<T> * elt) { T & LList<T>::addToLast(LList_elt<T> * elt) {
LList_elt<T> **curr_ptr = &_head; LList_elt<T> **curr_ptr = &_head;