Check if two Linked Lists are permutations of each other | C ++ program to check if 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 program to test above function ; First constructed linked list is : 12 -> 35 -> 1 -> 10 -> 34 -> 1 ; Second constructed linked list is : 35 -> 1 -> 12 -> 1 -> 10 -> 34
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; bool isPermutation ( struct Node * first , struct Node * second ) { int sum1 = 0 , sum2 = 0 , mul1 = 1 , mul2 = 1 ; struct Node * temp1 = first ; while ( temp1 != NULL ) { sum1 += temp1 -> data ; mul1 *= temp1 -> data ; temp1 = temp1 -> next ; } struct Node * temp2 = second ; while ( temp2 != NULL ) { sum2 += temp2 -> data ; mul2 *= temp2 -> data ; temp2 = temp2 -> next ; } return ( ( sum1 == sum2 ) && ( mul1 == mul2 ) ) ; } 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 main ( ) { struct Node * first = NULL ; push ( & first , 1 ) ; push ( & first , 34 ) ; push ( & first , 10 ) ; push ( & first , 1 ) ; push ( & first , 35 ) ; push ( & first , 12 ) ; struct Node * second = NULL ; push ( & second , 35 ) ; push ( & second , 1 ) ; push ( & second , 12 ) ; push ( & second , 1 ) ; push ( & second , 10 ) ; push ( & second , 34 ) ; if ( isPermutation ( first , second ) ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } return 0 ; }