I read the algorithm to add two numbers represented by a linked list from Crack The Coding Interview by Gayle Laakmann on page 108. If you do not have the book, the question, algorithm and code look like this:
Question
You have two numbers represented by a linked list, where each node contains one digit. The numbers are stored in reverse order, such that the first digit is at the head of the list. Write a function that adds two numbers and returns um as a linked list.
Example
Input: (3->1->5),(5->9->2)
Output: 8->0->8
Algorithm
- result.data = (node1 + node2 + previously migrate)% 10
- if node1 + node2> 10 then transfer 1 to the next addition
- add tails of two nodes running along the carry
Code
LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry) { if (l1 == null && l2 == null) { return null; } LinkedListNode result = new LinkedListNode(carry, null, null); int value = carry; if (l1 != null) { value += l1.data; } if (l2 != null) { value += l2.data; } result.data = value % 10; LinkedListNode more = addLists(l1 == null ? null : l1.next, l2 == null ? null : l2.next, value > 10 ? 1 : 0); result.setNext(more); return result; }
The obvious thing that comes to mind after looking at if (l1 == null && l2 == null) is that if both digits are zero and adding 999 + 999 still carries over. Will this lead to a wrong answer? If this leads to the correct answer, I do not understand how to do it. If this leads to a wrong answer, how can we get the right answer? Would change the first few lines to
LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry = null) { if (l1 == null && l2 == null) { return carry; }
do the trick?
source share