29ms C++ Solution using reverse


  • 0
    W
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            if(!l1) return l2;
            if(!l2) return l1;
            l1 = reverse(l1);
            l2 = reverse(l2);
            int add = 0, res = 0;
            ListNode *p = l1;
            ListNode *q = l2;
            ListNode *pre;
            while(p && q){
                res = p->val + q->val + add;
                if(res >= 10){
                    res -= 10; 
                    add = 1;
                }else add = 0;
                p -> val = res;
                q -> val = res;
                pre = p;
                p = p -> next;
                q = q -> next;
            }
            if(q){
                pre -> next = q;
                p = q;
            }
            while(p){
                res = p->val + add;
                if(res >= 10){
                    res -= 10; 
                    add = 1;
                }else add = 0;
                p -> val = res;
                pre = p;
                p = p -> next;
            }
            if(add){
                ListNode *node = new ListNode(1);
                pre -> next = node;
            }
            return reverse(l1);
        }
        
        ListNode* reverse(ListNode* head){
            ListNode *p, *q;
            p = head;
            head = NULL;
            while(p){
                q = head;
                head = p;
                p = p -> next;
                head -> next = q;
            }
            return head;
        }
    

Log in to reply
 

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