Adding numbers using Linked Lists

Introduction

Adding numbers has always been fascinating and you may think it to be the easiest mathematical operation possible. But believe me many a times that becomes the toughest problem to solve. Let us discuss this in more detail. It is really easy to add two numbers stored in two memory locations. The ALU provides you the option to use the ADD feature and store it on the DATA bus.

This is feasible when both the numbers can fit on the DATA bus one at a time. So, what about adding excessively large numbers, I know that the limit of BigInteger, Long, Double etc is too huge. But what if the numbers are bigger than that?

In such scenarios we need to use the linked list data structures to store the numbers and sum them. Having said that and agreeing on the usage of the linked list data structure, let us analyze the other challenges.

We cannot use a new auxiliary linked list.
The linked lists are singly linked, so it would be tough to adjust the carry to the previous node as you cannot move back.

The basic Idea for Adding numbers using Linked Lists

We always do additions from the right, the least significant digits. If the linked lists were given in reversed order, it would have been easier to add them and then reverse the resultant list. Basically we follow the four steps mentioned below.

  • Find the bigger linked list.
  • Reverse the two linked lists. You can understand the Reversing of linked list in O(N) time here.
  • Add the two linked lists node wise and store it in the nodes of the bigger list and adjust the carry to the next node.
  • Reverse the bigger list again

Here is a pictorial representation of the summation process.
Adding numbers using Linked Lists

Source Code – Adding numbers using Linked Lists

To download the complete source code, please visit the github link for techieme.

Analysis

Time Complexity –

We traverse the linked lists only once, so the total time would be proportional to the number of nodes in the larger list or we can say that it is O(N) where N is the number of digits in the larger number.

Space Complexity –

We are not using any auxiliary space other than the three pointers for reversing the linked list and one more space for keeping the carry. So we can say that it is constant O(1).

Don’t forget to subscribe to TechieMe to get updates on latest posts.