445. Add Two Numbers II
Problem
Two non-empty linked lists hold non-negative integers with the most significant digit first. Return their sum as a linked list in the same order.
Example: 7→2→4→3 + 5→6→4 → 7→8→0→7 (7243 + 564)
Constraints: follow-up: without reversing the input lists.
Most-significant digit first → push both lists' digits onto stacks, pop and add from the least significant, prepending each result node.
Complexity: O(m + n).
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
a, b = [], []
while l1:
a.append(l1.val); l1 = l1.next
while l2:
b.append(l2.val); l2 = l2.next
head, carry = None, 0
while a or b or carry:
s = carry + (a.pop() if a else 0) + (b.pop() if b else 0)
carry, d = divmod(s, 10)
head = ListNode(d, head)
return head
assert list_vals(Solution().addTwoNumbers(make_list([7, 2, 4, 3]), make_list([5, 6, 4]))) == [7, 8, 0, 7]
assert list_vals(Solution().addTwoNumbers(make_list([5]), make_list([5]))) == [1, 0]
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Deque<Integer> a = new ArrayDeque<>(), b = new ArrayDeque<>();
for (; l1 != null; l1 = l1.next) a.push(l1.val);
for (; l2 != null; l2 = l2.next) b.push(l2.val);
ListNode head = null;
int carry = 0;
while (!a.isEmpty() || !b.isEmpty() || carry != 0) {
int s = carry + (a.isEmpty() ? 0 : a.pop()) + (b.isEmpty() ? 0 : b.pop());
carry = s / 10;
head = new ListNode(s % 10, head);
}
return head;
}
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var a, b []int // digits, most significant first
for ; l1 != nil; l1 = l1.Next {
a = append(a, l1.Val)
}
for ; l2 != nil; l2 = l2.Next {
b = append(b, l2.Val)
}
var head *ListNode
carry := 0
for len(a) > 0 || len(b) > 0 || carry > 0 {
s := carry
if len(a) > 0 {
s += a[len(a)-1]
a = a[:len(a)-1]
}
if len(b) > 0 {
s += b[len(b)-1]
b = b[:len(b)-1]
}
carry = s / 10
head = &ListNode{Val: s % 10, Next: head} // build from the least significant end
}
return head
}