I'm trying here to count the number of the repeated occurrences in linked list
such that when my code will display ( 3 a , 2 c, 1 a) if I'm feeding it the list a->a->a->c->c->a
class Node
{
public:
char letter;
Node * next;
Node();
Node(char);
};
Using the following function I managed to count the occurrences but not the way I desired.
int Count(Node* h, char searchFor)
{
int count=0;
while(h)
{
if(h->letter==searchFor)
count++;
h=h->next;
}
return count;
}
In the main function
cout<<"a "<<Count( h, 'a')<<" c "<<Count(h,'c')<<"a "<<Count( h, 'a')<<endl;
will output (a 3, c 2, a 3) not ( a 3, c 2, a 1)
How can I pass the head to function such that it will return counts of all the nodes with similar chars ?
Looks like you do not want to count all chars, try this:
int Count(Node* h, char searchFor)
{
int count=0;
while(h)
{
if(h->letter==searchFor) {
++count;
}
else if(count > 0) {
break;
}
h=h->next;
}
return count;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.