Jack Faber
Jack Faber

Reputation: 37

Frequency in linked Lists

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

Answers (2)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33904

This condition: temp!=0 && !(temp-> info ==e) causes you to count up to the first of 2 things:

  1. The end of the list.
  2. The first time you reach e.

This is not your desired behavior, so you need to adjust the condition. What do we want?

  1. We go from the beginning of the list to the end, regardless of the number, so our for loop looks like: for(IntSLLNode *temp = head; temp; temp = temp->next).
  2. At each element we want to check if we have a number equal 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

ravenspoint
ravenspoint

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

Related Questions