Count duplicates in a given linked list | C ++ implementation of the approach ; Representation of node ; Function to insert a node at the beginning ; Function to count the number of duplicate nodes in the linked list ; Create a hash table insert head ; Traverse through remaining nodes ; Return the count of duplicate nodes ; Driver code
#include <iostream> NEW_LINE #include <unordered_set> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void insert ( Node * * head , int item ) { Node * temp = new Node ( ) ; temp -> data = item ; temp -> next = * head ; * head = temp ; } int countNode ( Node * head ) { if ( head == NULL ) return 0 ; ; unordered_set < int > s ; s . insert ( head -> data ) ; int count = 0 ; for ( Node * curr = head -> next ; curr != NULL ; curr = curr -> next ) { if ( s . find ( curr -> data ) != s . end ( ) ) count ++ ; s . insert ( curr -> data ) ; } return count ; } int main ( ) { Node * head = NULL ; insert ( & head , 5 ) ; insert ( & head , 7 ) ; insert ( & head , 5 ) ; insert ( & head , 1 ) ; insert ( & head , 7 ) ; cout << countNode ( head ) ; return 0 ; }