Compare numbers represented by Linked Lists | Structure for a linked list node ; A helper function to remove zeros from the start of the linked list ; A helper function to find the length of linked list ; 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 ; Set the data ; Link the old list after the new node ; Set the head to point to the new node ; Function to compare the numbers represented as linked lists ; Remover leading zeroes from the linked lists ; Since the number represented by a has a greater length , it will be greater ; If the lengths of two numbers are equal we have to check their magnitudes ; 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 we need to return zero ; The constructed linked lists are : a : 5 -> 6 -> 7 b : 2 -> 3 -> 3
class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } function removeLeadingZeros ( a ) { if ( a != null && a . data == 0 ) return removeLeadingZeros ( a . next ) ; else return a ; } function getSize ( a ) { let sz = 0 ; while ( a != null ) { a = a . next ; sz ++ ; } return sz ; } function push ( head_ref , new_data ) { var new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } function compare ( a , b ) { a = removeLeadingZeros ( a ) ; b = removeLeadingZeros ( b ) ; let lenA = getSize ( a ) ; let lenB = getSize ( b ) ; if ( lenA > lenB ) { return 1 ; } else if ( lenB > lenA ) { return - 1 ; } while ( a != null && b != null ) { if ( a . data > b . data ) return 1 ; else if ( a . data < b . data ) return - 1 ; a = a . next ; b = b . next ; } return 0 ; } var a = null ; a = push ( a , 7 ) ; a = push ( a , 6 ) ; a = push ( a , 5 ) ; var b = null ; b = push ( b , 3 ) ; b = push ( b , 3 ) ; b = push ( b , 2 ) ; document . write ( compare ( a , b ) ) ;