Reputation: 37
I'm trying to make a fn called frequency that returns the frequency of a given integer in the linked list. so far:
int IntSLList::frequency(int e)
{
int total = 0;
IntSLLNode *temp;
for (temp = head; temp!=0 && !(temp-> info ==e) ; temp = temp->next)
{
total++;
}
return total;
but the number that it returns (should return 1) but returns 8 my linked list has 10 elements (0-9
Upvotes: 1
Views: 171
Reputation: 33904
This condition: temp!=0 && !(temp-> info ==e)
causes you to count up to the first of 2 things:
e
.This is not your desired behavior, so you need to adjust the condition. What do we want?
for(IntSLLNode *temp = head; temp; temp = temp->next)
.e
: if (temp->info == e) {
total++;
}
This gives us the final loop:
int IntSLList::frequency(int e) {
int total = 0;
for (IntSLLNode *temp = head; temp; temp = temp->next) {
if( temp->info == e ) {
total++;
}
}
return total;
}
Upvotes: 1
Reputation: 20576
The check for equal to e should be done in the body of the for loop.
int IntSLList::frequency(int e)
{
int total = 0;
IntSLLNode *temp;
for (temp = head; temp!=0 ; temp = temp->next)
{
if( temp->info == e )
total++;
}
return total;
}
Upvotes: 1