Add Two Numbers
Add two numbers stored digit by digit in linked lists, ones digit first, the way you add on paper.
Two non-negative whole numbers are each stored in a linked list, one digit per node, with the ones digit in the first node. So 342 is stored as 2, then 4, then 3. Given the first nodes of the two lists, l1l2
Example 1
Output: [7, 0, 8]
Explanation: 342 + 465 = 807.
Example 2
Output: [0, 0, 0, 1]
Explanation: 999 + 1 = 1000, so the sum has one digit more than either number.
The Idea
To add 342 and 465 on paper, you write one number under the other and start on the right: the ones column, then the tens, then the hundreds. Each column gives one digit of the answer. When a column adds up to 10 or more, you write the last digit and pass the extra 1 to the next column. That extra 1 is called the carry.
Here the numbers come as linked lists. A linked list is a chain of small objects called nodes. Each node holds one value and a link, named nextnextnull
In Example 1, l1l2
Each column in the picture holds one node of l1l2
So storing the ones digit first gives exactly the order column addition needs. Walking both lists from their heads, one node at a time, visits the columns just as on paper, and each step adds one node to the result.
Example 2 adds a twist. In 999 + 1, every column carries, and after the hundreds column both lists have ended while a carry of 1 is still waiting. On paper you would write that 1 in front, making 1000. The result list needs one more node than the longer input list.
Solution Approach
Turning that idea into code means first seeing why a plain conversion to a number falls short. Then four things need settling: lists of different lengths, a column's digit and carry, when to stop, and how to build the result list.
Converting the lists to numbers
Why not read each list into a Java longlong
Lists of different lengths
What if one list ends before the other? Take [1, 8][0]l2
The digit and the carry of a column
How does a column's sum become a digit and a carry? Two digits and a carry add up to at most 9 + 9 + 1 = 19. The digit to write is sum % 10sum / 10
When to stop
When is the addition finished? Not as soon as both lists have ended: in Example 2 a carry of 1 is still waiting then. So the loop keeps going while l1l2
Building the result list
How do new digits get onto the end of the result? A variable named tailtail.nexttailnext
Java Solution
The method addTwoNumbers
- First, create the placeholder node
, pointdummy at it, and settail to 0.carry - The parameters
andl1 point at the current node of each list and becomel2 when that list ends. Loop whilenull has a node, orl1 has a node, orl2 is not 0. Each pass of the loop is one column, and it starts withcarry set tosum .carry - If
still has a node, add its value tol1 and movesum to the next node. Do the same forl1 .l2 - Attach a new node holding
tosum % 10 , movetail.next onto it, and settail tocarry for the next column.sum / 10 - When the loop ends, return
, the node with the ones digit of the sum.dummy.next
Next to the method, the class has a small ListNodebuildshow[7, 0, 8]main
public class AddTwoNumbers {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0); // placeholder before the first digit
ListNode tail = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
tail.next = new ListNode(sum % 10); // the digit for this column
tail = tail.next;
carry = sum / 10; // carried to the next column
}
return dummy.next;
}
static ListNode build(int... digits) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (int d : digits) {
tail.next = new ListNode(d);
tail = tail.next;
}
return dummy.next;
}
static String show(ListNode node) {
StringBuilder sb = new StringBuilder("[");
for (; node != null; node = node.next) {
sb.append(node.val).append(node.next != null ? ", " : "");
}
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(addTwoNumbers(build(2, 4, 3), build(5, 6, 4))));
System.out.println(show(addTwoNumbers(build(9, 9, 9), build(1))));
System.out.println(show(addTwoNumbers(build(1, 8), build(0))));
System.out.println(show(addTwoNumbers(build(5), build(5))));
System.out.println(show(addTwoNumbers(build(0), build(0))));
}
}
Running it prints:
[7, 0, 8]
[0, 0, 0, 1]
[1, 8]
[0, 1]
[0]
Look at the second line, [0, 0, 0, 1]carry != 0[0, 0, 0][0]
The third line, [1, 8]l2null[0, 1][0]l1
Complexity
The method walks both lists once, side by side, and does a fixed amount of work per column.
- Time: O(max(m, n)) for lists of m and n nodes: each pass of the loop handles one column, there are as many columns as nodes in the longer list, and a final carry adds at most one more pass.
- Space: O(1) besides the result. The result list has at most max(m, n) + 1 nodes. Apart from it, the method keeps only
,dummy ,tail andsum .carry
When the digits are stored most significant first, see