My C++ solution that doesn't create a new linked list


  • 0
    F
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            int flag = 0;
            int sum = 0;
            ListNode* pointer1 = l1;
            ListNode* pointer2 = l2;
            ListNode* result;
            while(pointer1 && pointer2)
            {
                pointer1 = pointer1->next;
                pointer2 = pointer2->next;
            }
            if(!pointer1)
                result = l2;
            else
                result = l1;
            ListNode* back = result;
            
            while(l1 || l2)
            {
                sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + flag;
                flag = sum / 10;
                result->val = sum % 10;
                l1? l1 = l1->next : l1;
                l2? l2 = l2->next : l2;
                result->next? result = result->next : result;
            }
            if(flag == 1)
            {
                ListNode* haha = new ListNode(1);
                result->next = haha;
            }
            return back;
        }
    

    I use the longer list between l1 and l2 to be my new list.


Log in to reply
 

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