Opening the reading…
Opening the reading…
LINKED LIST › LINKED LIST (PART 1)
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Each list stores the number backwards, so the first node is the units digit, the next node is the tens digit, and so on. That is exactly the order in which manual addition works: add the current digits, write the result digit, and carry the remaining value into the next column. No list reversal is needed.
At every position, add three values: the digit from the first list if one exists, the digit from the second list if one exists, and the carry from the previous position. The new node stores sum modulo 10, while sum divided by 10 becomes the carry for the next position. If one list ends first, treat its missing digits as zero.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(max(n1, n2)) | Each existing input node is read exactly once, and the loop performs at most one additional iteration for a final carry. The shorter list contributes no extra traversal after it ends, so the longer list determines the bound. |
| Space | O(1) extra space | The algorithm stores only pointers, the carry, and the current sum while building the required output list. The returned result nodes are output storage and are excluded from the extra-space bound; the output can contain max(n1, n2) or max(n1, n2) + 1 nodes. |
#include <cstddef>
using namespace std;
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
int carry = 0;
while (l1 || l2 || carry) {
int sum = carry;
if (l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur->next;
}
return dummy->next;
}
};The loop condition carries the main correctness detail: it includes carry as well as the two input pointers. For example, after adding 9 and 1, both lists may be exhausted while carry is still 1, so the loop must run once more to create the leading result digit. The two null checks let the same body handle equal-length lists, unequal-length lists, and the final carry without duplicated cases.