Minimal memory usage solution with only two additional pointers.


  • 0
    H
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* RNode=new ListNode(0);
            ListNode* PNode=RNode;
            while(true)
            {
                if(l2==nullptr)
                {
                    PNode->val+=l1->val;
                    l1=l1->next;
                }
                else if(l1==nullptr)
                {
                    PNode->val+=l2->val;
                    l2=l2->next;
                }
                else
                {
                    PNode->val+=l1->val;
                    l1=l1->next;
                    PNode->val+=l2->val;
                    l2=l2->next;
                }
                //cout<<"Before digit: "<<PNode->val<<endl;
                if(PNode->val>=10)
                {
                    PNode->next=new ListNode(PNode->val/10);
                    PNode->val=PNode->val%10;
                }
                if(l1==nullptr&&l2==nullptr)
                {
                    break;
                }
                if(PNode->next==nullptr)
                {
                    PNode->next=new ListNode(0);
                }
                PNode=PNode->next;
            }
            return RNode;
        }
    };

  • 0
    H

    This solution used condition check to avoid using additional sentry pointer.
    Meanwhile all unnecessary condition check had been removed.


Log in to reply
 

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