Two given numbers below represented by linked lists:
9 -> 9 -> 9 -> 9 (9999)
5 -> 5 (55)
Addition of these should be:
1 -> 0 -> 0 -> 5 -> 4 (10054)
Category: Data Structure And Algorithms | Tags: C#, Interview Question |
Two given numbers below represented by linked lists:
9 -> 9 -> 9 -> 9 (9999)
5 -> 5 (55)
Addition of these should be:
1 -> 0 -> 0 -> 5 -> 4 (10054)
Answers:
If we have to add two numbers on paper we do like:
9999
+0055
------------
10054
So in linked list if two are having same length then we can add simply else we have to add prefix of zero's before smaller one to make them same length then we can use recursion to go to the end of both and start adding them.
Node structure:
To get length of a list:
To add prefix to the smaller linked list:
To print a linked list:
To add two lists:
Calling all above from main method:
Output:
9999 + 0055 = 10054