Identical Linked Lists | An iterative C ++ program to check if two linked lists are identical or not ; Structure for a linked list node ; Returns true if linked lists a and b are identical , otherwise false ; If we reach here , then a and b are not NULL and their data is same , so move to next nodes in both lists ; If linked lists are identical , then ' a ' and ' b ' must be NULL at this point . ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the 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 ; The constructed linked lists are : a : 3 -> 2 -> 1 b : 3 -> 2 -> 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; bool areIdentical ( struct Node * a , struct Node * b ) { while ( a != NULL && b != NULL ) { if ( a -> data != b -> data ) return false ; a = a -> next ; b = b -> next ; } return ( a == NULL && b == NULL ) ; } 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 * a = NULL ; struct Node * b = NULL ; push ( & a , 1 ) ; push ( & a , 2 ) ; push ( & a , 3 ) ; push ( & b , 1 ) ; push ( & b , 2 ) ; push ( & b , 3 ) ; if ( areIdentical ( a , b ) ) cout << " Identical " ; else cout << " Not ▁ identical " ; return 0 ; }