Simple C++ solution with O(1) space


  • 0
    K
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode *head1 = l1, *head2 = l2;
            while(l1 && l2) {
                l1 = l1->next; l2 = l2->next;
            }
            ListNode* head3 = l1?head1:head2;
            ListNode* head4 = head3;
            int i  = l1?1:0;
            int carry = 0;
            while(head1 || head2) {
                int sum = ((head1?head1->val:0) + (head2?head2->val:0) + (carry?carry:0));
                i?head1->val = sum%10:head2->val = sum%10;
                head1 = head1?head1->next:NULL; head2 = head2?head2->next:NULL;
                carry = sum/10;
            }
            if(carry) {
                while(head4->next){
                    head4 = head4->next;
                }
                head4->next = new ListNode(carry);
            }
            return head3;
        }
    

Log in to reply
 

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