I was trying to write a program for the problem I mentioned above, the numbers (i.e the lists) can be of unequal length, I was not able to figure out a way to do this other than the most commonly thought of approach i.e
- reverse list-1
- reverse list-2
- find the sum and store it in a new list represented by list-3
- reverse the list.
The complexity of this should be of the O(n+m). Is there anyway to reduce it, or do it better?
Ideally the first thing I would do is store the numbers in reverse digit order, so 43,712 is stored as:
It makes arithmetic operations much easier.
Displaying a number can be done either iteratively or more simply with a recursive algorithm. Note: all this assumes singly-linked lists.
Edit: But you’ve since stated you have no choice in the storage format. As such, your best bet is to reverse both the lists, do the addition and then reverse the result.