Write a program to print the total number of occurrences of a given item in the linked list
#include <iostream>
using namespace std;
class LinkedList {
public:
int item;
LinkedList* nextNode;
};
void push(LinkedList** head, int data)
{
LinkedList* node = new LinkedList();
node->item = data;
node->nextNode = (*head);
(*head) = node;
}
int count_number(LinkedList* head, int search)
{
LinkedList* currentNode = head;
int i = 0;
while (currentNode != NULL) {
if (currentNode->item == search)
i++;
currentNode = currentNode->nextNode;
}
return i;
}
int main()
{
LinkedList* list = NULL;
push(&list, 1);
push(&list, 3);
push(&list, 1);
push(&list, 2);
push(&list, 1);
cout << "Total number of occurrences of 1 is: " << count_number(list, 1);
return 0;
}
Comments
Leave a comment