First common element in two linked lists | Java 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 java . util . * ; class GFG { static class Node { int data ; Node next ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static int firstCommon ( Node head1 , Node head2 ) { for ( ; head1 != null ; head1 = head1 . next ) for ( Node p = head2 ; p != null ; p = p . next ) if ( p . data == head1 . data ) return head1 . data ; return 0 ; } public static void main ( String [ ] args ) { Node head1 = null ; head1 = push ( head1 , 20 ) ; head1 = push ( head1 , 5 ) ; head1 = push ( head1 , 15 ) ; head1 = push ( head1 , 10 ) ; Node head2 = null ; head2 = push ( head2 , 10 ) ; head2 = push ( head2 , 2 ) ; head2 = push ( head2 , 15 ) ; head2 = push ( head2 , 8 ) ; System . out . println ( firstCommon ( head1 , head2 ) ) ; } }