NullPointerException error Java


  • 0
    F

    /

    **
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode a=new ListNode(0);
            int c=0;
            while((l1!=null) | (l2!=null) )
            { 
              if(l1==null)
              a.val=l2.val+c;
              else if(l2==null)
              a.val=l1.val+c;
              else
                a.val=l1.val+l2.val+c;
                if(a.val>9)
                 {  
                    c=(a.val-(a.val%10))/10;
                    a.val=a.val%10;
                 }
                 else
                  c=0;
                  l1=l1.next;
                  l2=l2.next;
                  a=a.next;
            }
            return a;
      }
      }
    

    Runtime Error Message: Line 18: java.lang.NullPointerException

    Last executed input: [1,8], [0]

    I dont understand why i am getting nullpointerexception


  • 0
    L

    Line a=a.next;
    But a.next is NULL


Log in to reply
 

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