Count duplicates in a given linked list | Python3 implementation of the approach ; Representation of node ; Function to push a node at the beginning ; Function to count the number of duplicate nodes in the linked list ; print ( 1 ) Starting from the next node ; print ( 2 ) If some duplicate node is found ; Return the count of duplicate nodes ; Driver code
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head , item ) : NEW_LINE INDENT temp = Node ( item ) ; NEW_LINE temp . data = item ; NEW_LINE temp . next = head ; NEW_LINE head = temp ; NEW_LINE return head ; NEW_LINE DEDENT def countNode ( head ) : NEW_LINE INDENT count = 0 NEW_LINE while ( head . next != None ) : NEW_LINE INDENT ptr = head . next NEW_LINE while ( ptr != None ) : NEW_LINE INDENT if ( head . data == ptr . data ) : NEW_LINE INDENT count = count + 1 NEW_LINE break NEW_LINE DEDENT ptr = ptr . next NEW_LINE DEDENT head = head . next NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None ; NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 7 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 1 ) NEW_LINE head = push ( head , 7 ) NEW_LINE print ( countNode ( head ) ) NEW_LINE DEDENT