I'm currently struggling to understand why my removeElement() function is not actually removing the node from the LinkedList. Here is my code:
template<typename T>
void LinkedList<T>::remove(T element) {
if (isEmpty()) {
cout << "List is empty.";
}
else if (head == tail) {
cout << "Only One" << endl;
head == NULL;
tail == NULL;
}
else {
cout << "Multiple in List" << endl;
Node<T>* curr = head;
Node<T>* prev = curr;
while (curr != NULL) {
if (curr->element == element) {
cout << "deleting " << element << endl;
prev = curr->next;
delete curr;
}
else {
prev = curr;
curr = curr->next;
}
}
if(curr == NULL) {
cout << element << " is not in list" << endl;
}
}
}
This code effectively locates the element in the linked list, but for whatever reason deleting the current node doesn't actually remove the element from the list; even after having reassigned my previous to the next node. I'm going to keep looking for documentation in the meantime which may shed some light on what is almost certainly a dumb oversight on my side, but any help would be greatly appreciated.
Updated code now gives me a bounty of wonderful string_alloc errors:
template<typename T>
void LinkedList<T>::remove(T element) {
Node<T>* current = head;
Node<T>* previous = current;
if (isEmpty()) {
cout << "List is empty.";
}
else if (head == tail) {
cout << "Only One" << endl;
}
else {
cout << "Multiple Nodes in List" << endl;
while (current != NULL) {
if (current->element == element) {
previous->next = current->next;
delete current;
break;
}
else {
previous = current;
current = current->next;
}
}
}
}
I suspect at this point that it has more to do with the way I'm transitioning from node to node, specifically:
previous = current;
current = current -> next;
I still have not properly created a case for single-elements in the list, the errors are only thrown when I attempt to delete any node.