Your editorial solution does not check for trailing zeroes and creates new list rather than in place


#1

CODE WHICH IS IN PLACE AND REMOVES TRAILING ZEROES AS WELL :arrow_down:

 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {
    ListNode* ptr1 = A,*ptr2 = B;
    int lenA = 0, lenB =0;
    while(ptr1){
        lenA++;
        ptr1 =ptr1->next;
    }
    while(ptr2){
        lenB++;
        ptr2 =ptr2->next;
    }
    if(lenB>lenA)
        return addTwoNumbers(B,A);
    int c = 0;
    ListNode* prev;
    ptr1 = A,ptr2 =B;
    while(ptr1 && ptr2){
        int temp = ptr1->val + ptr2->val + c;
        ptr1->val = (ptr1->val + ptr2->val + c)%10;
        c = temp/10;
        prev = ptr1;
        ptr1 = ptr1->next;
        ptr2 = ptr2->next;
    }
    ptr1 = prev;
    while(ptr1->next){
        int temp = ptr1->next->val +c;
        ptr1->next->val = (ptr1->next->val + c)%10;
        c = temp/10;
        ptr1 =ptr1->next;
    }
    if(c==1)
    {
       ListNode * temp = new  ListNode(c);
       ptr1->next = temp;
    }
    //remove trailing zeroes
    ptr1 = A;
    int flag = 0;
    ListNode* pptr = NULL;
    while(ptr1){
        if(ptr1->val == 0){
            if(flag ==0){
                flag = 1;
                pptr = ptr1;
            }    
        }
        else{
            flag = 0;
            pptr = NULL;
        }
        if(flag == 0)
            prev = ptr1;
        ptr1 =ptr1->next;
    }
    if(pptr){
        prev->next = NULL;
        free(pptr);
    }
    return A;
            
 }

HOPE THIS HELPS :slight_smile: