I know how to remove a node from the front of a singly linked list, but I have no idea how to remove one from any arbitrary location.
In my specific problem, I continue to pass an integer value x into each node in the linked list. I can add and delete, but there is a function I need to write where if I've identified two x's that are the same, I delete the other instance.
You can crawl your list, find the previous node, and have that previous node connect to the next node, then delete the current node. It's a bit easier in a doubly linked list because you can simply connect the nodes together then perish.
void Singly_Linked_List :: add_unique_age_to_the_front(int x)
{
//Insert a new age to the front of the singly linked list
Node* addUnique=head;
if(!test_age_contained_in_singly_linked_list(x)) //Call the test age function for a case where it is not true no matter what
{
Node* newNode2;
newNode2= new Node(x);
newNode2->next=head;
head=newNode2;
}
}
void Singly_Linked_List :: remove_age_from_singly_linked_list(int x)
{
Node* removeAge=head;
Node* prevNode=NULL;
while(removeAge!=NULL)
{
if(test_age_contained_in_singly_linked_list(x))
{
prevNode->next=removeAge->next;
delete removeAge;
}
prevNode=removeAge;
removeAge=removeAge->next;
}
}
Based on add_unique_age_to_the_front(), it looks like test_age_contained_in_singly_linked_list() returns true if the argument is anywhere in the list. But that isn't what you want to test in remove_age_from_singly_linked_list(). You want to remove a specific node if that node has the age.
Your error at line 29 occurs because test_age_contaned_in_singly_lionked_list() returns true on the first call, but in that case, prevNode is NULL, so prevNode->next generates a memory error.
When you remove the node, don't forget to delete it so you don't leak the memory.
Change line 26 to check whether removeAge contains the age x. Since you haven't shown the declaration of class Node, I can't say exactly how to do this.
Then you'll have to deal with the possbility that prevNode is NULL. In that case you're removing from the head of the list.