Add Two Numbers II
Add two numbers stored in linked lists with the most significant digit first, using two stacks.
Two non-negative whole numbers are each stored in a linked list, one digit per node, with the most significant digit in the first node. So 7243 is stored as 7, then 2, then 4, then 3. Given the first nodes of the two lists, l1l2
Example 1
Output: [7, 8, 0, 7]
Explanation: 7243 + 564 = 7807.
Example 2
Output: [8, 0, 7]
Explanation: 243 + 564 = 807.
The Idea
To add 7243 and 564 on paper, you write 564 under the last three digits of 7243 and start on the right. The ones column gives 3 + 4 = 7. The tens column gives 4 + 6 = 10, so you write 0 and pass the extra 1, called the carry, to the hundreds column. The answer, 7807, is written from right to left.
Here each number is a linked list: a chain of nodes, where each node holds one digit and a link, named nextnextnulll1l2
So where are the ones digits? Look at the top half of the picture below. l1l2l1l2
Addition has to start with those orange nodes, and a walk from the head reaches them last. How can we read a list from the back when we can only walk it forward? Walk it once and put each digit on a stack. A stack is a pile of values: you push a value onto the top and pop the top value off, so the value pushed last comes off first.
The bottom left of the picture shows the stacks after both walks. The stack for l1l2
The rows under "Popped in pairs, ones column first" follow that order: 3 + 4 = 7, then 4 + 6 = 10, which gives the digit 0 and a carry of 1. Then come 2 + 5 + 1 = 8, and finally 7 on its own, because the stack for l2
One question is left. The digits come out ones digit first: 7, 0, 8, and then the thousands digit 7. The answer must start with the thousands digit. So each new digit goes in front of the digits already built, and the result row in the picture reads 7, 8, 0, 7.
Solution Approach
Before the stacks, it is worth seeing why the lists cannot simply be turned into numbers. After that, three things need settling: how to store the digits, how a column gives its digit and carry, and how to put each digit in front. Reversing the lists in place is an optional way to save memory.
Why not plain numbers
Could we read 7, 2, 4, 3 into the number 7243, add 564, and split 7807 back into nodes? Only while the numbers fit in a Java long
Storing the digits on stacks
Which Java class should hold the digits? ArrayDequejava.utilpushpopisEmptyStack
One column: digit and carry
What does one column write, and what does it pass on? Its sum is never more than 19, two 9s plus a carry of 1. The digit is sum % 10sum / 10
When one stack runs empty, as the stack for l2
Putting each digit in front
How do you put a node in front of a list? Make the new node with its nextheadnull
Reversing the lists instead
The stacks hold a copy of every digit. Is there a way without them? If both lists are reversed in place first, by turning each next
Java Solution
The method addTwoNumbers
- First, create two stacks,
ands1 , ass2 objects. A loop walksArrayDeque from its head and pushes each digit ontol1 , and a second loop does the same fors1 andl2 .s2 - Set
, the first node of the result, tohead , andnull to 0.carry - Loop while
is not empty, ors1 is not empty, ors2 is not 0. Each pass is one column: it startscarry atsum , then pops a digit from each stack that still has one and adds it.carry - Put a new node holding
in front, withsum % 10 , and sethead = new ListNode(sum % 10, head) tocarry for the next column.sum / 10 - When the loop ends, return
, which now holds the most significant digit of the sum.head
Next to the method, the class has a small ListNodebuildshow[8, 0, 7]mainl1
import java.util.ArrayDeque;
import java.util.Deque;
public class AddTwoNumbersII {
static class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Deque<Integer> s1 = new ArrayDeque<>(); // digits of l1, ones digit on top
Deque<Integer> s2 = new ArrayDeque<>();
for (ListNode n = l1; n != null; n = n.next) {
s1.push(n.val);
}
for (ListNode n = l2; n != null; n = n.next) {
s2.push(n.val);
}
ListNode head = null;
int carry = 0;
while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) {
int sum = carry;
if (!s1.isEmpty()) {
sum += s1.pop();
}
if (!s2.isEmpty()) {
sum += s2.pop();
}
head = new ListNode(sum % 10, head); // new digit goes in front
carry = sum / 10;
}
return head;
}
static ListNode build(int... digits) {
ListNode head = null;
for (int i = digits.length - 1; i >= 0; i--) {
head = new ListNode(digits[i], head);
}
return head;
}
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) {
ListNode l1 = build(7, 2, 4, 3);
System.out.println(show(addTwoNumbers(l1, build(5, 6, 4))));
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(0), build(0))));
System.out.println("l1 afterwards: " + show(l1));
}
}
Running it prints:
[7, 8, 0, 7]
[8, 0, 7]
[1, 0, 0, 0]
[0]
l1 afterwards: [7, 2, 4, 3]
Look at the third line, [1, 0, 0, 0]carry != 0
The fourth line shows that 0 + 0 still gives one node, [0]l1[7, 2, 4, 3]
Putting each digit in front is what keeps [7, 8, 0, 7][7, 0, 8, 7]
Complexity
The method walks each list once to fill the stacks, then pops every digit once while adding.
- Time: O(m + n) for lists of m and n nodes: the two walks push m and n digits, the adding loop pops each of them once, and a final carry adds at most one more pass.
- Space: O(m + n) besides the result, because the two stacks hold a copy of every digit of both lists. Reversing the lists in place instead brings this down to O(1), at the price of changing the input.
When the digits are stored ones digit first, no stacks are needed: see