Created
September 22, 2019 20:09
-
-
Save danielgospodinow/331adb72574c065feac9d6a0fc77b071 to your computer and use it in GitHub Desktop.
Linked List insert 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
/** | |
* Insert an element to the data structure at a specified index. | |
* | |
* @tparam T type | |
* @param item item to insert | |
* @param index index at which to insert | |
*/ | |
template<typename T> | |
void LinkedList<T>::insert(const T &item, const int index) { | |
if (index < 0 || index >= _size) { | |
// If the index is out of bounds, throw an exception. | |
throw std::invalid_argument("Index out of bounds"); | |
} else { | |
// Create a box which wraps the new element. | |
auto *const newNode = new Node<T>(item); | |
// Initialize an index counter and two pointers to | |
// track two consecutive elements. | |
int indexCounter = 0; | |
Node<T> *prev = nullptr; | |
Node<T> *iter = _head; | |
// While we haven't reached the desired index, | |
// move both element pointers to the right. | |
while (indexCounter++ < index) { | |
prev = iter; | |
iter = iter->next; | |
} | |
if (prev && iter) { | |
// If we have both pointers pointing to an element, | |
// then we're somewhere after the first element in the | |
// data structure, so make the current element's previous | |
// point to the new element and make the new element point | |
// to the current one. | |
prev->next = newNode; | |
newNode->next = iter; | |
// Increase the data structure's size. | |
++_size; | |
} else if (iter) { | |
// If only the pointer to the current element is | |
// not null, then we're at the first element of the | |
// data structure (the head), so make the new element | |
// be the head and point it to the old head element. | |
_head = newNode; | |
_head->next = iter; | |
// Increase the data structure's size. | |
++_size; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment