Add Two Numbers
linked-list • math
Medium
You are given two non-empty linked lists representing two non-negative integers. Add the two numbers and return the sum as a linked list.
Examples
Input
l1 = [2,4,3], l2 = [5,6,4]
Output
[7,0,8]
342 + 465 = 807 -> [7,0,8]
Input
l1 = [0], l2 = [0]
Output
[0]
0 + 0 = 0
Solution
Traverse both lists simultaneously, add corresponding digits plus carry.
Create new nodes for the resulting digits and propagate carry to the next position.
Time: , Space: for the result list.
Add Two Numbers
linked-list • math
Medium
You are given two non-empty linked lists representing two non-negative integers. Add the two numbers and return the sum as a linked list.
Examples
Input
l1 = [2,4,3], l2 = [5,6,4]
Output
[7,0,8]
342 + 465 = 807 -> [7,0,8]
Input
l1 = [0], l2 = [0]
Output
[0]
0 + 0 = 0
Solution
Traverse both lists simultaneously, add corresponding digits plus carry.
Create new nodes for the resulting digits and propagate carry to the next position.
Time: , Space: for the result list.
Code Solution
add-two-numbers.cpp
cpp
1#include <iostream>2#include <vector>3using namespace std;45struct ListNode { int val; ListNode* next; ListNode(int x): val(x), next(nullptr) {} };67ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {8ListNode dummy(0);9ListNode* p = &dummy;10int carry = 0;11while (l1 || l2 || carry) {12int sum = carry;13if (l1) { sum += l1->val; l1 = l1->next; }14if (l2) { sum += l2->val; l2 = l2->next; }15carry = sum / 10;16p->next = new ListNode(sum % 10);17p = p->next;18}19return dummy.next;20}