LinkedList: Add a prepend() method
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2022-12-17 15:27:16 +01:00
parent c5220cbf64
commit f5de9c5589
Signed by: apio
GPG Key ID: B8A7D06E42258954

View File

@ -45,12 +45,18 @@ template <typename T> class DoublyLinkedListNode
m_last_node->m_next_node = m_next_node; m_last_node->m_next_node = m_next_node;
} }
void add_to_list(SelfType* end_node) void append_to_list(SelfType* end_node)
{ {
end_node->m_next_node = this; end_node->m_next_node = this;
this->m_last_node = end_node; this->m_last_node = end_node;
} }
void prepend_to_list(SelfType* start_node)
{
start_node->m_last_node = this;
this->m_next_node = start_node;
}
friend class DoublyLinkedList<T>; friend class DoublyLinkedList<T>;
}; };
@ -65,7 +71,7 @@ template <typename T> class DoublyLinkedList
{ {
Node* const node = extract_node(ptr); Node* const node = extract_node(ptr);
if (!m_start_node) m_start_node = node; if (!m_start_node) m_start_node = node;
if (m_end_node) node->add_to_list(m_end_node); if (m_end_node) node->append_to_list(m_end_node);
else else
{ {
node->set_next(nullptr); node->set_next(nullptr);
@ -76,6 +82,20 @@ template <typename T> class DoublyLinkedList
m_count++; m_count++;
} }
void prepend(T* ptr)
{
Node* const node = extract_node(ptr);
if (m_start_node) node->prepend_to_list(m_start_node);
else
{
node->set_next(nullptr);
node->set_last(nullptr);
}
m_start_node = node;
m_count++;
}
void add_after(T* base, T* ptr) void add_after(T* base, T* ptr)
{ {
Node* const new_node = extract_node(ptr); Node* const new_node = extract_node(ptr);