Created
September 22, 2019 20:07
-
-
Save danielgospodinow/1a2731e33e1bc099cb44964569097ed4 to your computer and use it in GitHub Desktop.
LinkedList add operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add a new item to the data structure. | |
* | |
* @tparam T type | |
* @param item the new item | |
*/ | |
template<typename T> | |
void LinkedList<T>::add(const T &item) { | |
// Create a box which wraps the new element. | |
auto *const newNode = new Node<T>(item); | |
if (!_head) { | |
// If the head is NULL then the data structure is empty, | |
// so make the first element (the head) be the new element. | |
// Do the same for the tail element. | |
_head = newNode; | |
_tail = newNode; | |
// Increase the size of the data structure. | |
++_size; | |
} else { | |
// If the head is not null, then we have some elements | |
// to work with and also the tail is not null. | |
// Attach the new node to the last element (the tail) and | |
// make it the new tail. | |
_tail->next = newNode; | |
_tail = newNode; | |
// Increase the size of the data structure. | |
++_size; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment