C++ solution without using reverse !


  • 0
    Z
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            if (!l1)    return l2;
            if (!l2)    return l1;
            int cnt1 = 0, cnt2 = 0;
            ListNode* p = l1;
            while (p)
            {
                cnt1++;
                p = p->next;
            }
            p = l2;
            while (p)
            {
                cnt2++;
                p = p->next;
            }
            if (cnt1<cnt2)  return addTwoNumbers(l2,l1);
            int c = help(l1,l2,cnt1,cnt2);
            if (c>0)
            {
                ListNode* head = new ListNode(c);
                head->next = l1;
                return head;
            }
            else
                return l1;
        }
        int help(ListNode *l1, ListNode *l2, int cnt1, int cnt2)
        {
            if (!l1) return 0;
            int t = 0;
            if (cnt1>cnt2)
                t = help(l1->next,l2,cnt1-1,cnt2)+l1->val;
            else
                t = help(l1->next,l2->next,cnt1-1,cnt2-1)+l1->val+l2->val;
            l1->val = t%10;
            return t/10;
        }
    

Log in to reply
 

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