Algo-Sim › Linked Lists
Add Two Numbers
Medium · Linked Lists · step through it in Java, Python and C++ on your own input
Add two numbers stored as reversed digit lists, building the sum list node by node with a carry.
Problem
Two non-negative integers are stored as linked lists of digits, least significant digit first (342 is 2 → 4 → 3). Return their sum as a list in the same format.
Constraints
- 1 ≤ nodes in each list ≤ 100
- 0 ≤ Node.val ≤ 9
- No leading zeros, except the number 0 itself
- Numbers can be 100 digits long, too large for any integer type
Edge cases to test
- A final carry adds a node:
5 + 5 - Different lengths
- One list is just
0
Follow-up questions
- What if the digits are stored most significant first?
- Reverse both lists first, or push digits onto two stacks and build the result from the front (LC 445): O(m + n).
- Why not convert to integers?
- The lists can be longer than any fixed-width integer.
Solution
Java
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 sum = carry;
if (l1 != null) { sum += l1.val; l1 = l1.next; }
if (l2 != null) { sum += l2.val; l2 = l2.next; }
carry = sum / 10;
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
return dummy.next;
}Python
def add_two_numbers(l1, l2):
dummy = tail = ListNode()
carry = 0
while l1 or l2 or carry:
total = carry
if l1:
total += l1.val
l1 = l1.next
if l2:
total += l2.val
l2 = l2.next
carry = total // 10
tail.next = ListNode(total % 10)
tail = tail.next
return dummy.nextC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *dummy = new ListNode(0), *tail = dummy;
int carry = 0;
while (l1 != nullptr || l2 != nullptr || carry != 0) {
int sum = carry;
if (l1 != nullptr) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != nullptr) {
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
return dummy->next;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)