Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
1
Indexable
Never
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode(0);
        ListNode curr = l3;
        int carry = 0;
        while(l1!=null && l2!=null){
            int val = l1.val + l2.val + carry;
            if(carry == 1){
                carry = 0;
            }
            if(val > 9){
                val = val % 10;
                carry = 1;
            }
            curr.val = val; //NPE HERE
            curr = curr.next;
            l1 = l1.next;
            l2 = l2.next;
        }

        while(l1!=null){
            int val = l1.val + carry;
            if(carry == 1){
                carry = 0;
            }
            if(val > 9){
                val = val % 10;
                carry = 1;
            }
            curr.val = val;
            curr = curr.next;
            l1 = l1.next;
        }

        while(l2!=null){
            int val = l2.val + carry;
            if(carry == 1){
                carry = 0;
            }
            if(val > 9){
                val = val % 10;
                carry = 1;
            }
            curr.val = val;
            curr = curr.next;
            l2 = l2.next;
        }

        return l3;
    }
}