Computer Science, asked by melissaineza8, 11 months ago

Given a linked list and an integer value; write a function that count the occurrence of the value in
the liked List and return the occurrence value to the calling function.?

Answers

Answered by Raghav1330
0

Answer:

The code is explained code but this is the algorithm

1. Initialize the count as zero.

2. Loop execution through each element of linked list:

a) If element data is equal to the passed number then count is incremented

3. Return the count value.

Explanation:

*/ A C++ program to count occurrences in a linked list /*

#include <iostream>

using namespace std;

/* Creating Link list node */

class Node {

public:

int data;

Node* next;

};

/* Given a pointer to pointer reference to the head of the list and an int is used to push a new node on the front

of the list. */

void push(Node** head_ref, int new_data)

{

/* allocation of node */

Node* new_node = new Node();

/* putting it in the data */

new_node->data = new_data;

/* linking the old list off the new node */

new_node->next = (*head_ref);

/* moving the head to point to the new created node */

(*head_ref) = new_node;

}

/* Counting the no. of frequency of a node

named search_for in a linked list head*/

int count(Node* head, int search_for)

{

Node* current = head;

int count = 0;

while (current != NULL) {

if (current->data == search_for)

count++;

current = current->next;

}

return count;

}

/* a simple program to test count function*/

int main()

{

/* Start with the empty list */

Node* head = NULL;

/* Use push() to construct below list

1->2->1->3->1 */

push(&head, 1);

push(&head, 3);

push(&head, 1);

push(&head, 2);

push(&head, 1);

/* Checking the count function */

cout << "count of 1 is " << count(head, 1);

return 0;

}

Similar questions