C++ Code for the twoList Add AC


  • 1
    L

    if (!l1)
    return l2;
    if (!l2)
    return l1;
    ListNode* p = l1; // first one
    ListNode* q = l2;
    ListNode* ptr = NULL;
    int len1 = 0, len2 = 0, count = 0;;
    while (p != NULL) { p = p->next; len1++;}
    while (q != NULL) { q = q->next; len2++;}

        if (len1 >= len2) {
            p = l1;
            q = l2;
        }
        else {
            p = l2;
            q = l1;
        }
        while (p != NULL) {
            if (q != NULL) {
                p->val += q->val + count;
                count = 0;
                if (p->val/10 > 0) {
                    count++;
                    p->val %= 10;
                }
                if (p->next == NULL)
                    ptr =  p;
                p = p->next;
                q = q->next;
    
            }
            else {
                p->val += count;
                 count = 0;
                 if (p->val/10 > 0) {
                    count++;
                    p->val %= 10;
                }
                if (p->next == NULL)
                    ptr =  p;
                p =  p->next;
            }
        }
    
        if (p == NULL && count >  0)
            ptr->next = new ListNode(count);
    
        if (len1 >= len2)
            return l1;
        else
            return l2;
    }

Log in to reply
 

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