Add Two Numbers Stored as Linked Lists
Problem
Two non-negative integers are given as linked lists where the head holds the least significant digit. Return their sum as the same kind of list. Walk both lists in lockstep, summing digits and a running carry; whenever a list runs out, treat its digit as 0. After the loop, if carry > 0, append a final digit.
Input
l1 = 2→4→3, l2 = 5→6→4Output
7→0→8342 + 465 = 807, written least-significant-first.
def add_two_numbers(l1, l2):
dummy = ListNode()
tail, carry = dummy, 0
while l1 or l2 or carry:
a = l1.val if l1 else 0
b = l2.val if l2 else 0
s = a + b + carry
carry, digit = divmod(s, 10)
tail.next = ListNode(digit)
tail = tail.next
if l1: l1 = l1.next
if l2: l2 = l2.next
return dummy.next
function addTwoNumbers(l1, l2) {
const dummy = { val: 0, next: null };
let tail = dummy, carry = 0;
while (l1 || l2 || carry) {
const a = l1 ? l1.val : 0;
const b = l2 ? l2.val : 0;
const sum = a + b + carry;
carry = Math.floor(sum / 10);
tail.next = { val: sum % 10, next: null };
tail = tail.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
return dummy.next;
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0), tail = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int a = l1 != null ? l1.val : 0;
int b = l2 != null ? l2.val : 0;
int sum = a + b + carry;
carry = sum / 10;
tail.next = new ListNode(sum % 10);
tail = tail.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
return dummy.next;
}
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode* tail = &dummy;
int carry = 0;
while (l1 || l2 || carry) {
int a = l1 ? l1->val : 0;
int b = l2 ? l2->val : 0;
int sum = a + b + carry;
carry = sum / 10;
tail->next = new ListNode(sum % 10);
tail = tail->next;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
return dummy.next;
}