Add two numbers as a linked list

Question

You are given two linked-lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You can also check on LeetCode 2. Add Two Numbers

Example:

1
2
3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solution

Thinking about the add operation in math and we know we need to calculate the number from backward and add 1 if exists sum of two digits are greater that 10. And repeat the process until we finished all nodes. But we have to care about the situation (9, 9, 9) + (1) -> (0, 0, 0, 1) and at the end, we have to add one more node.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Time: O(max(m, n))
// m -> # of nodes in l1, n -> # of nodes in l2
// Space: O(1)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;// go through the whole process.
int carry = 0;
while (l1 != null || l2 != null) {
if (l1 != null) {
carry += l1.val;
l1 = l1.next;
}

if (l2 != null) {
carry += l2.val;
l2 = l2.next;
}
cur.next = new ListNode(carry % 10);
cur = cur.next;
carry /= 10;
}
// in case of '9,9,9 + 1,' -> '0,0,0,1'
if (carry != 0) {
cur.next = new ListNode(carry % 10);
}
return dummy.next;
}