#How to resolve this error??

4 messages · Page 1 of 1 (latest)

vale holly
#

..

turbid mistBOT
#

Hey, @vale holly!
Please remember to /close this post once your question has been answered!

vale holly
#
import java.util.LinkedList;

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 Add_two_numbers {
    static ListNode l1 = new ListNode();
    static ListNode l2 = new ListNode();
    static{
        l1.val = 2;
        l1.next.val = 4;
        l1.next.next.val = 3;
        l2.val = 5;
        l2.next.val = 6;
        l2.next.next.val = 4;
    }
    static LinkedList<Integer> List = new LinkedList<>();
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode Node = new ListNode();
        if(l1==null&&l2==null){
            return null;
        }
        else if(l1==null){
            return addTwoNumbers(l1,l2.next);
        }
        else if (l2==null){
            return addTwoNumbers(l1.next,l2);
        }
        Node.val = l1.val+l2.val;
        List.addFirst(Node.val);
        return Node;
    }
    public static void main(String []args){
        addTwoNumbers(l1,l2);
        System.out.println(List);
    }
}```
Question--> https://leetcode.com/problems/add-two-numbers/
`Caused by: java.lang.NullPointerException: 
Cannot assign field "val" because "Add_two_numbers.l1.next" is null
    at Add_two_numbers.<clinit>(ListNode.java:15)`.