Reputation: 27
I'm required to traverse through a singly linked list and find the negative nodes, delete them and return the number of delete nodes.
This is the code i have so far, but I always get counter=1 returned from the function
Is there anything wrong in the for loops and if statements, or is it something else
bool IntSLList::DeleteNegativeNodes()
{
int counter=0;
if(IsEmpty() == true)
counter++;
if(head->val<0)
{
DeleteFromHead();
counter++;
}
if(tail->val<0)
{
DeleteFromTail();
counter++;
}
IntSLLNode *node, *pred, *tmp;
node = pred = NULL;
for(pred = head, node = head->next;
node != NULL;
node = node->next, pred = pred->next)
{
if(node->val<0)
{
node->flag = 1;
}
}
for(tmp = head; tmp != NULL; tmp = tmp->next)
{
if(tmp->flag==1)
counter++;
delete tmp;
}
return counter;
}
int main()
{
int n,x,z;
IntSLList list1;
cout <<"Insert number of nodes u'd like inserted in list" << endl;
cin >> n;
for(int i=0;i<n;i++)
{
cin >> x;
list1.AddToTail(x);
}
z=list1.DeleteNegativeNodes();
cout << "Number of negative deletes nodes is : " << z << endl;
}
Upvotes: 0
Views: 368
Reputation: 6427
The problem is in the type of the return value. Check the signature of the method:
bool IntSLList::DeleteNegativeNodes()
Return type is bool
there. When you return counter
of type int
from your method it's implicitly converted to bool
. Zero value becomes false
. All other values become true
.
On the caller side:
z=list1.DeleteNegativeNodes();
bool
value is implicitly converted to int
. Because of it you get 1
.
Change the return type of DeleteNegativeNodes
to int
to fix the problem.
Upvotes: 1
Reputation: 48
In the second for you have
if(tmp->flag==1)
And I think you have to use
if(node->flag==1)
Upvotes: 0