Add two numbers (digits in reverse order)
Add two numbers stored as linked lists of digits, least-significant digit first, carrying into the next node like adding on paper.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Walk both lists together like adding two numbers by hand: add the two current digits plus any carry, write down the last digit, and carry the rest into the next column. Keep going as long as either list still has a digit or there is a carry left over.
Code
public static ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
var dummy = new ListNode(0);
ListNode tail = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry;
carry = sum / 10;
tail.next = new ListNode(sum % 10);
tail = tail.next;
l1 = l1?.next; l2 = l2?.next;
}
return dummy.next;
}static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int sum = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;
carry = sum / 10;
tail.next = new ListNode(sum % 10);
tail = tail.next;
l1 = l1 != null ? l1.next : null; l2 = l2 != null ? l2.next : null;
}
return dummy.next;
}ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode* tail = &dummy;
int carry = 0;
while (l1 || l2 || carry) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
carry = sum / 10;
tail->next = new ListNode(sum % 10);
tail = tail->next;
l1 = l1 ? l1->next : nullptr; l2 = l2 ? l2->next : nullptr;
}
return dummy.next;
}def add_two_numbers(l1: ListNode | None, l2: ListNode | None) -> ListNode | None:
dummy = ListNode(0)
tail = dummy
carry = 0
while l1 or l2 or carry:
total = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
carry = total // 10
tail.next = ListNode(total % 10)
tail = tail.next
l1 = l1.next if l1 else None; l2 = l2.next if l2 else None
return dummy.nextTips
- A dummy head avoids a special case for the first digit of the result.
- Do not stop as soon as both lists end — a leftover carry still needs one more node, e.g. 5 + 5 = 10.
In the .NET library
l1?.val ?? 0 reads a digit as 0 once that list has run out, so the shorter list does not need padding with explicit zero nodes.