Count duplicates in a given linked list | Java 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
import java . util . HashSet ; class GFG { static class Node { int data ; Node next ; } ; static Node head ; static void insert ( Node ref_head , int item ) { Node temp = new Node ( ) ; temp . data = item ; temp . next = ref_head ; head = temp ; } static int countNode ( Node head ) { if ( head == null ) return 0 ; ; HashSet < Integer > s = new HashSet < > ( ) ; s . add ( head . data ) ; int count = 0 ; for ( Node curr = head . next ; curr != null ; curr = curr . next ) { if ( s . contains ( curr . data ) ) count ++ ; s . add ( curr . data ) ; } return count ; } public static void main ( String [ ] args ) { insert ( head , 5 ) ; insert ( head , 7 ) ; insert ( head , 5 ) ; insert ( head , 1 ) ; insert ( head , 7 ) ; System . out . println ( countNode ( head ) ) ; } }