C++,36ms,DummyHead Solution


  • 0
    W
    class Solution {
    public:
    int pollOver(ListNode** L) {
        if(*L == nullptr)
            return 0;
        else{
            int ret = (*L)->val;
            *L=(*L)->next;
            return ret;
        }
    } 
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* pReturn = new ListNode(-1);
            ListNode* pt = pReturn;
            int carry=0;
            while (l1 != nullptr || l2 != nullptr)
            {
                pt->next = new ListNode{-1};
                pt->next->val = pollOver(&l1) + pollOver(&l2) + carry;
                if (pt->next->val > 9)
                {
                    carry = 1;
                    pt->next->val -= 10;
                }
                else
                    carry = 0;
                
                pt = pt->next;
            }
            
            if(carry)
                pt->next = new ListNode{1};
            pt = pReturn;
            pReturn= pReturn->next;
            delete pt;
            return pReturn;
    }
    };

Log in to reply
 

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