Simple Linked List Q.

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";
}
rather than mentioning the dupe why do not you take a look at it?!!! and maybe help me out you f*** idiot
Last edited on
@Eyad
You posted the same question 3 times in 2 days, dont call someone an idiot when they call you on it. Now you look like an idiot.

EDIT: And the answer has already been given to you, all you should have to do is remove the return on line 18
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
Node* one = new Node(5);
	Node* two = new Node(5);
	Node* three = new Node(3);
	Node* four = new Node(4);
	Node* five = new Node(5);
	Node* six = new Node(6);
	h=one;
	one->next=two;
	two->next=three;
	three->next=four;
	four->next=five;
	five->next=six;
	DelAcc(h, 5);


i tried these values, and it is not working correctly, it only deletes the second and the fifth but not the first!!! and you keep telling me that you gave me the answer and i kept saying it not working correctly.
i will marke it as solved and i'll submit whatever i got thanks anyways.
That's another bug, but not the main problem. You never delete the head, unless it's the only node and it's a 5.
i kept saying it not working correctly


And, yet you keep posting exactly the same code.

You say:
it only deletes the second and the fifth but not the first!!!
so you should look at the code that modifies the "first" (head) value.

 
	if(!head->next && head->value==X) {delete head; head=NULL; return;}


Consider the control expression. The only time head->value == X is evaluated is when !head->next evaluates to a non-zero value. The only time !head->next evaluates to a non-zero value is when head->next is NULL. This means that the only time you check to see if head contains X is when head is the only member of the list.
thanks buddy, i already submitted the code, and i am sorry if i offended you or any one in any way.
Topic archived. No new replies allowed.