First common element in two linked lists | Python3 program to find first common element in two unsorted linked list ; Link list node ; A utility function to insert a node at the beginning of a linked list ; Returns the first repeating element in linked list ; Traverse through every node of first list ; If current node is present in second list ; If no common node ; 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_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def firstCommon ( head1 , head2 ) : NEW_LINE INDENT while ( head1 != None ) : NEW_LINE INDENT p = head2 NEW_LINE while ( p != None ) : NEW_LINE INDENT if ( p . data == head1 . data ) : NEW_LINE INDENT return head1 . data NEW_LINE DEDENT p = p . next NEW_LINE DEDENT head1 = head1 . next NEW_LINE DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head1 = None NEW_LINE head1 = push ( head1 , 20 ) NEW_LINE head1 = push ( head1 , 5 ) NEW_LINE head1 = push ( head1 , 15 ) NEW_LINE head1 = push ( head1 , 10 ) NEW_LINE head2 = None NEW_LINE head2 = push ( head2 , 10 ) NEW_LINE head2 = push ( head2 , 2 ) NEW_LINE head2 = push ( head2 , 15 ) NEW_LINE head2 = push ( head2 , 8 ) NEW_LINE print ( firstCommon ( head1 , head2 ) ) NEW_LINE DEDENT