Thursday 13 March 2014

Addition Of Two Numbers Using Linked Lists


Another very frequently searched algorithm is to add two very long numbers (in the order of zillions) using Linked Lists.


IMPLEMENTATION:


We use the Linked List to implement such a logic. Here, we make use of the fact that “int” in java has the range -2^31 to 2^31 which is 10 digits long. Therefore, every node in the list can hold maximum upto 10 digits. If the number has more than 10 digits, the More Significant Digits are pushed in the previous node. Thus 2 Lists are created for 2 numbers and they are then added node-by-node. The carry, if generated is added to the next pair of nodes to get the proper answer.


As usual, we have used our own version of Linked List to make the addition, deletion, and searching nodes processes transparent.





The main Addition class which calls the above class is as follows:

NOTE: We have created the program keeping in mind only positive integers. Floating point numbers may/may not work in this program depending on the number!
NOTE: A more elegent solution will be to input the number from Most Significant Digits and keep pushing the nodes into a stack. Thus, we will have 2 stacks for 2 numbers. Now, all we need to do is add the node pointed by the top of each stack with each other and and keep pushing it into a "result" stack.

No comments:

Post a Comment