Count pairs from two linked lists whose sum is equal to a given value | A Linked list node ; function to count all pairs from both the linked lists whose sum is equal to a given value ; traverse the 1 st linked list ; for each node of 1 st list traverse the 2 nd list ; if sum of pair is equal to ' x ' increment count ; required count of pairs ; Driver program to test above
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 . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def countPairs ( head1 , head2 , x ) : NEW_LINE INDENT count = 0 NEW_LINE p1 = head1 NEW_LINE while ( p1 != None ) : NEW_LINE INDENT p2 = head2 NEW_LINE while ( p2 != None ) : NEW_LINE INDENT if ( ( p1 . data + p2 . data ) == x ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT p2 = p2 . next NEW_LINE DEDENT p1 = p1 . next NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head1 = None NEW_LINE head2 = None NEW_LINE head1 = push ( head1 , 7 ) NEW_LINE head1 = push ( head1 , 5 ) NEW_LINE head1 = push ( head1 , 1 ) NEW_LINE head1 = push ( head1 , 3 ) NEW_LINE head2 = push ( head2 , 3 ) NEW_LINE head2 = push ( head2 , 5 ) NEW_LINE head2 = push ( head2 , 2 ) NEW_LINE head2 = push ( head2 , 8 ) NEW_LINE x = 10 NEW_LINE print ( " Count ▁ = ▁ " , countPairs ( head1 , head2 , x ) ) NEW_LINE DEDENT