JavaWeb笔记——if语句中空指针报错

题目:

删除排序链表中的重复元素
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2

示例 2:

输入: 1->1->2->3->3
输出: 1->2->3


/**
 * 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 deleteDuplicates(ListNode head) {
       
        ListNode next  = new ListNode(0);
        ListNode cur = head;
        while(cur.next != null && cur != null){
            
            next = cur.next;
            if(cur.val == next.val){
                cur.next = next.next;
                
            }
            else{
                 cur = cur.next;

            }
             

        }
        return head;

    }

   
}

大多数输入都没有问题,但是当输入是[]时————
报错:Line 17: java.lang.NullPointerException

想了很久,逻辑上没有问题,但是为什么在if语句那里报错呢?

原来是if语句中两个语句判定的顺序,只要把if中的两个条件判定顺序交换一下就行了。
因为cur.next是不存在的,如果先判断cur.next != 0就会报NullPointerException
&&这个与运算,只要左边第一个条件判断为FALSE就不会再去判断右边的条件。

最后的代码:

/**
 * 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 deleteDuplicates(ListNode head) {
       
        //ListNode next  = new ListNode(0);
        ListNode cur = head;
        while( cur != null &&cur.next != null){
            //next = cur.next;
            if(cur.val == cur.next.val){
                cur.next = cur.next.next;
                
            }
            else{
                 cur = cur.next;

            }
             

        }
        return head;

    }

   
}
posted @ 2021-02-20 11:31  Raybu  阅读(240)  评论(0)    收藏  举报