I know that plenty of questions have been asked regarding deleting a node from linked list. But my mind got stuck at a point and I am unable to clear my confusion.
I have a linked list with nodes 1,2,2 in it. And I want to delete nodes of 2 from it. My code is deleting only first node of 2 not the second one. In short I want to delete all the nodes that match to the key give by the user. Here is my code:
void LinkedList::Delete(int key)
{
if(head == 0)
return;
if(head->data == key)
{
Node *p = head;
head = head->next;
delete p;
}
else
{
Node *prev = 0;
Node *temp = head;
while(temp!=0)
{
if(temp->data == key)
{
Node *q = temp;
temp = temp->next;
prev = temp;
delete q;
}
else
{
prev = temp;
temp = temp->next;
}
}
}
}
If I comment out the else
portion then it gives me the access violation error at the last line i.e temp=temp->next
and I know the issue is that to which node it should point if it is at the last node!