Last active
May 30, 2019 01:05
-
-
Save xseano/4d17f13044a3b5fed2de52e1cde542e2 to your computer and use it in GitHub Desktop.
Linked List Add Node
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
/** | |
* @brief Add Node of data "T" to end of list | |
* | |
* @param targetData the data to add to the list | |
*/ | |
template <class T> | |
void LinkedList<T>::addNode(T targetData) | |
{ | |
Node<T> *temp = new Node<T>(targetData); // create a temp Node | |
if (head<T> == NULL) | |
{ | |
// head is nonexistent, assign the first node to the new data | |
temp->next = temp; // no head so make new node the head | |
head<T> = temp; // set global head to newly created node | |
return; | |
} | |
// head does exist, set new ptr | |
Node<T> *tmp = head<T>; | |
while(tmp->next != head<T>) // while the next ptr doesnt point to head (aka iterate to tail) | |
{ | |
// keep iterating until we hit the node before the last node (the one that points to head) | |
tmp = tmp->next; | |
} | |
tmp->next = temp; // from the second to last node, obtain last node and point to new node as new tail node | |
temp->next = head<T>; // set the new node's next ptr to head since it is the tail node now | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment