First common element in two linked lists | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int firstCommon ( struct Node * head1 , struct 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 ; } int main ( ) { struct Node * head1 = NULL ; push ( & head1 , 20 ) ; push ( & head1 , 5 ) ; push ( & head1 , 15 ) ; push ( & head1 , 10 ) ; struct Node * head2 = NULL ; push ( & head2 , 10 ) ; push ( & head2 , 2 ) ; push ( & head2 , 15 ) ; push ( & head2 , 8 ) ; cout << firstCommon ( head1 , head2 ) ; return 0 ; }