## Search Your Topic

Tuesday, 11 July 2017 12:33

## Write a function that counts the number of times a given int occurs in a Linked List

Written by
Rate this item

Given a singly linked list and a key, count number of occurrences of given key in linked list. For example, if given linked list is 1->2->1->2->1->3->1 and given key is 1, then output should be 4.

Algorithm:

```1. Initialize count as zero.
2. Loop through each element of linked list:
a) If element data is equal to the passed number then
increment the count.
3. Return count. ```

`// C/C++ program to count occurrences in a linked list`
`#include<stdio.h>`
`#include<stdlib.h>`

`/* Link list node */`
`struct` `Node`
`{`
`    ``int` `data;`
`    ``struct` `Node* next;`
`};`

`/* Given a reference (pointer to pointer) to the head`
`  ``of a list and an int, push a new node on the front`
`  ``of the list. */`
`void` `push(``struct` `Node** head_ref, ``int` `new_data)`
`{`
`    ``/* allocate node */`
`    ``struct` `Node* new_node =`
`            ``(``struct` `Node*) ``malloc``(``sizeof``(``struct` `Node));`

`    ``/* put in the data  */`
`    ``new_node->data  = new_data;`

`    ``/* link the old list off the new node */`
`    ``new_node->next = (*head_ref);`

`    ``/* move the head to point to the new node */`
`    ``(*head_ref)    = new_node;`
`}`

`/* Counts the no. of occurences of a node`
`   ``(search_for) in a linked list (head)*/`
`int` `count(``struct` `Node* head, ``int` `search_for)`
`{`
`    ``struct` `Node* current = head;`
`    ``int` `count = 0;`
`    ``while` `(current != NULL)`
`    ``{`
`        ``if` `(current->data == search_for)`
`           ``count++;`
`        ``current = current->next;`
`    ``}`
`    ``return` `count;`
`}`

`/* Drier program to test count function*/`
`int` `main()`
`{`
`    ``/* Start with the empty list */`
`    ``struct` `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);`

`    ``/* Check the count function */`
`    ``printf``(``"count of 1 is %d"``, count(head, 1));`
`    ``return` `0;`
`}`

`Output:`

`count of 1 is 3`

Time Complexity: O(n)
Auxiliary Space: O(1) 