Check if two Linked Lists are permutations of each other | A linked list node ; Function to check if two linked lists are permutations of each other first : reference to head of first linked list second : reference to head of second linked list ; Variables to keep track of sum and multiplication ; Traversing through linked list and calculating sum and multiply ; Traversing through linked list and calculating sum and multiply ; Function to add a node at the beginning of Linked List ; Allocate node ; Put in the data ; Link the old list off the new node ; Move the head to point to the new node ; Driver Code ; First constructed linked list is : 12 . 35 . 1 . 10 . 34 . 1 ; Second constructed linked list is : 35 . 1 . 12 . 1 . 10 . 34
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def isPermutation ( first , second ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE mul1 = 1 NEW_LINE mul2 = 1 NEW_LINE temp1 = first NEW_LINE while ( temp1 != None ) : NEW_LINE INDENT sum1 += temp1 . data NEW_LINE mul1 *= temp1 . data NEW_LINE temp1 = temp1 . next NEW_LINE DEDENT temp2 = second NEW_LINE while ( temp2 != None ) : NEW_LINE INDENT sum2 += temp2 . data NEW_LINE mul2 *= temp2 . data NEW_LINE temp2 = temp2 . next NEW_LINE DEDENT return ( ( sum1 == sum2 ) and ( mul1 == mul2 ) ) NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) 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 if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT first = None NEW_LINE first = push ( first , 1 ) NEW_LINE first = push ( first , 34 ) NEW_LINE first = push ( first , 10 ) NEW_LINE first = push ( first , 1 ) NEW_LINE first = push ( first , 35 ) NEW_LINE first = push ( first , 12 ) NEW_LINE second = None NEW_LINE second = push ( second , 35 ) NEW_LINE second = push ( second , 1 ) NEW_LINE second = push ( second , 12 ) NEW_LINE second = push ( second , 1 ) NEW_LINE second = push ( second , 10 ) NEW_LINE second = push ( second , 34 ) NEW_LINE if ( isPermutation ( first , second ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT