Description
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Algorithm
Use variables to track carry and simulate the bitwise addition process starting from the header
- Time complexity:
- Space complexity:
C++ Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// Use variables to track carry
// Simulate the bitwise addition process starting from the header
auto p = l1, q = l2, dummy = new ListNode(-1);
auto curr = dummy;
int t = 0;
while (p || q || t) {
int sum = t;
if (p) {sum += p->val; p = p->next;}
if (q) {sum += q->val; q = q->next;}
curr->next = new ListNode(sum % 10);
curr = curr->next;
t = sum / 10;
}
curr->next = NULL; // Actually constructor defined it
return dummy->next;
}
};