Skip to content

Latest commit

 

History

History
88 lines (78 loc) · 2.14 KB

File metadata and controls

88 lines (78 loc) · 2.14 KB

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 contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Screen Shot 2021-10-27 at 12 01 24 AM

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode dummyHead;
        ListNode* curr = &dummyHead;
        int sum = 0;

        while(l1 || l2) {
            if(l1) {
                sum += l1->val;
                l1 = l1->next;
            }
            if(l2) {
                sum += l2->val;
                l2 = l2->next;
            }
            curr->next = new ListNode(sum % 10);
            curr = curr->next;
            sum /= 10;
        }
        if(sum) {
            curr->next = new ListNode(sum);
        }

        return dummyHead.next;
    }
};

JavaScript

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    let head = new ListNode();
    let curr = head;
    let sum = 0;
    
    while(l1 || l2) {
        if(l1) {
            sum += l1.val;
            l1 = l1.next;
        }
        if(l2) {
            sum += l2.val;
            l2 = l2.next;
        }
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        sum = sum > 9 ? 1 : 0;
    }
    if(sum) {
        curr.next = new ListNode(sum);
    }
    return head.next
};