C++, Python Solutions. O(n) runtime, O(1) space.


  • 0

    C++

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode res(0);
        ListNode* res_tmp = &res;
        int val = 0;
        while(l1 || l2) {
            if(l1) {
                val += l1->val;
                l1 = l1->next;
            }
            if(l2) {
                val += l2->val;
                l2 = l2->next;
            }
            res_tmp->next = new ListNode(val % 10);
            res_tmp = res_tmp->next;
            val /= 10;
        }
        if(val != 0)
            res_tmp->next = new ListNode(val);
        return res.next;
    }
    

    Python

    def addTwoNumbers(self, l1, l2):
        res = ListNode(0)
        l1_tmp, l2_tmp, res_tmp = l1, l2, res
        val = 0
        while l1_tmp or l2_tmp:
            if l1_tmp:
                val += l1_tmp.val
                l1_tmp = l1_tmp.next
            if l2_tmp:
                val += l2_tmp.val
                l2_tmp = l2_tmp.next
            res_tmp.next = ListNode(val % 10)
            res_tmp = res_tmp.next
            val /= 10
        if val != 0:
            res_tmp.next = ListNode(val)
        return res.next
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.