delete all occurrences of x from a linked list

Given a number x, write a program to delete all occurrences of x from a linked list
in one iteration. That is, you can not scan the list more than once.

It only deletes the first occurrence of X, can someone help fixing it please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void DelAcc(Node*& head, int X)
{
	if((!head)||(!head->next && head->value!=X))
	{
		cout<<"could not find "<<X<<" in the list\n";
		return;
	}
	if(!head->next && head->value==X) {delete head; head=NULL; return;}
	Node* tmp = head;
	Node* t;
	while(tmp->next)
	{
		if(tmp->next->value == X)
		{
			t = tmp->next;
			tmp->next = tmp->next->next;
			delete t;
			return;
		}
		tmp=tmp->next;
	}
	cout<<"could not find "<<X<<" in the list\n";
}
1
2
3
4
5
6
7
if(tmp->next->value == X)
		{
			t = tmp->next;
			tmp->next = tmp->next->next;
			delete t;
			return;
		}


{delete head; head=NULL; return;}

Questions?
Last edited on
covering probability!
COME ON GUYZ!!!
Are you sure that the function isn't working? This will say
"Could not find << X << in the list"
every time because the cout statement is below the loops. Just a suggestion. :)
So again, what do you think the return in line 18 does? Especially in regard to your question?
i removed it and i ran the code, but still it only deletes the first occurrence of X
Last edited on
If the occurrences are adjacent, that is because you're skipping two elements when erasing one. You forgot an else.
thx for trying to help. but i do not get it. anyways i'll try to figure it out myself.
Topic archived. No new replies allowed.