My constant space complexity solution


  • 0
    H
    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       if (l1 == null) return l2;
       if (l2 == null) return l1;
              
    
        ListNode head1 = new ListNode(0);
        ListNode head2 = new ListNode(0);
    
        head1.next = l1;
        head2.next = l2;
        ListNode pre1 = head1, pre2 = head2;
    
        int carry = 0;
        while (l1 != null && l2 != null){
            carry = l1.val + l2.val + carry;
            l1.val = carry % 10;
            carry /= 10;
    
            l1 = l1.next;
            l2 = l2.next;
            pre1 = pre1.next;
            pre2 = pre2.next;
        }
        
        ListNode ser = null;
        if (l1 == null && l2 == null){
            if (carry == 1)
                pre1.next = new ListNode(1);
            return head1.next;
        }
        else if (l1 == null){
            pre1.next = pre2.next;
            pre2.next = null;
            ser = l2;
        }else {
            ser = l1;
        }
    
        while (ser.next != null){
            carry = ser.val + carry;
            ser.val = carry % 10;
            carry /= 10;
            if (carry == 0)
                break;
            ser = ser.next;
        }
    
        carry = ser.val + carry;
        ser.val = carry % 10;
        carry /= 10;
    
        if (carry == 1)
            ser.next = new ListNode(1);
    
        return head1.next;
    }
    

    }


Log in to reply
 

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