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 None and their data is same , so move to next nodes in both lists ; If linked lists are identical , then we need to return zero ; Driver code ; The constructed linked lists are : a : 5.6 . 7 b : 2.3 . 3
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def removeLeadingZeros ( a ) : NEW_LINE INDENT if ( a != None and a . data == 0 ) : NEW_LINE INDENT return removeLeadingZeros ( a . next ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return a ; NEW_LINE DEDENT DEDENT def getSize ( a ) : NEW_LINE INDENT sz = 0 ; NEW_LINE while ( a != None ) : NEW_LINE INDENT a = a . next ; NEW_LINE sz += 1 NEW_LINE DEDENT return sz ; 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 def compare ( a , b ) : NEW_LINE INDENT a = removeLeadingZeros ( a ) ; NEW_LINE b = removeLeadingZeros ( b ) ; NEW_LINE lenA = getSize ( a ) ; NEW_LINE lenB = getSize ( b ) ; NEW_LINE if ( lenA > lenB ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( lenB > lenA ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT while ( a != None and b != None ) : NEW_LINE INDENT if ( a . data > b . data ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( a . data < b . data ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT a = a . next ; NEW_LINE b = b . next ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = None ; NEW_LINE a = push ( a , 7 ) ; NEW_LINE a = push ( a , 6 ) ; NEW_LINE a = push ( a , 5 ) ; NEW_LINE b = None ; NEW_LINE b = push ( b , 3 ) ; NEW_LINE b = push ( b , 3 ) ; NEW_LINE b = push ( b , 2 ) ; NEW_LINE print ( compare ( a , b ) ) NEW_LINE DEDENT