CODE
template <class T>
void remove_each (Node<T>* &head, T const& x)
{
Node<T> *q = head;
while (q->next) {
if (head) {
if (head->value == x) {
Node<T> *tempo = head;
head = head->next;
delete temp;
}
else {
while (q->next) {
if (q->next->value == x) {
Node<T> *temp = q->next;
q->next = q->next->next;
delete temp;
}
else
q = q->next;
}
}
}
else {
while (q->next) {
if (q->next->value == x) {
Node<T> *temp = q->next;
q->next = q->next->next;
delete temp;
}
else
q = q->next;
}
}
}
}
I'm attempting to construct a single-linked list implementation class for a project and the above function takes head node and a certain value the user desires to remove from the list. As far as Visual Studio is concerned, it works for every case except when the first two elements are values to be removed. The code segment where the error occurs is the following:
CODE
if (q->next->value == x) { //This line
Node<T> *temp = q->next;
q->next = q->next->next;
delete temp;
}
However, no error occurs if I allow a memory leak in the first check
CODE
if (head->value == x) {
Node<T> *tempo = head;
head = head->next;
delete temp;
}
by leaving out the delete and having just the redirection of head.
The error I receive is "Access violation reading location ______" and while I know that it means it's reading past the available nodes, I cannot figure out how it does while passing the previous while loop test of while(q->next).
Any input would be appreciated.