Simple C++ solution with reverse


  • 0
    K
    class Solution {
    public:
        ListNode* new_reverse(ListNode* l){
            ListNode* root = NULL;
            while(l){
                ListNode* temp = new ListNode(l->val);
                temp->next = root;
                root = temp;
                l = l->next;
            }
            return root;
        }
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* p = new_reverse(l1);
            ListNode* q = new_reverse(l2);
            int temp = 0;
            ListNode* root = NULL;
            ListNode* temp1 =NULL;
            while(q || p) {
                if(q && p) temp1 = new ListNode((p->val + q->val + temp)%10), temp = (p->val + q->val + temp)/10, p = p->next, q = q->next;
                else if(q && !p) temp1 = new ListNode((q->val + temp)%10), temp = (q->val + temp)/10, q = q->next;
                else if(p && !q) temp1 = new ListNode((p->val + temp)%10), temp = (p->val + temp)/10, p = p->next;
                temp1->next = root;
                root = temp1;
            }
            if(temp) {
                temp1 = new ListNode(temp);
                temp1->next = root;
                root = temp1;
            }
            return root;
        }
    };
    

Log in to reply
 

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