Pretty short and concise c++


  • 0
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode* tail  = new ListNode(-1);
        ListNode* head  = tail;
        
        while(l1 || l2){
            int res = (l1?l1->val:0) + (l2?l2->val:0) + carry;
            tail->next = new ListNode(res>9? res-10:res);  tail = tail->next;  carry = res>9? 1: 0;
            if(l1)l1=l1->next; if(l2)l2=l2->next;
        }
        if(carry) tail->next = new ListNode(1);
        
        return head->next;

Log in to reply
 

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