Q:
Write a Count() function that counts the number of times a given int occurs in a list.
A:
int Count(struct node* head, int searchFor) {
struct node* current = head;
int count = 0;
while (current != NULL) {
if (current->data == searchFor) count++;
current = current->next;
}
return count;
}
Alternately, the iteration may be coded with a for loop instead of a while...
int Count2(struct node* head, int searchFor) {
struct node* current;
int count = 0;
for (current = head; current != NULL; current = current->next) {
if (current->data == searchFor) count++;
}
return count;
}
Thursday, April 22, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment