Identical Linked Lists | Linked list Node ; head of list ; 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 . ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node ; Driver program to test above functions ; The constructed linked lists are : llist1 : 3 -> 2 -> 1 llist2 : 3 -> 2 -> 1
class Node { int data ; Node next ; Node ( int d ) { data = d ; next = null ; } } class LinkedList { Node head ; boolean areIdentical ( LinkedList listb ) { Node a = this . head , b = listb . head ; 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 ( int new_data ) { Node new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } public static void main ( String args [ ] ) { LinkedList llist1 = new LinkedList ( ) ; LinkedList llist2 = new LinkedList ( ) ; llist1 . push ( 1 ) ; llist1 . push ( 2 ) ; llist1 . push ( 3 ) ; llist2 . push ( 1 ) ; llist2 . push ( 2 ) ; llist2 . push ( 3 ) ; if ( llist1 . areIdentical ( llist2 ) == true ) System . out . println ( " Identical ▁ " ) ; else System . out . println ( " Not ▁ identical ▁ " ) ; } }