java数据结构与算法

为什么这个循环条件while(cur.next!=null && cur.next.next!=null){}写成cur.next.next!=null会报错,
cur.next.next!=null所以cur.next!=null也成立吧?


class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next==null){
            return head;
        }
        ListNode head1 = new ListNode(-1);
        ListNode cur = head1;
        head1.next = head;
        ListNode temp0 = null;
        ListNode temp1 = null;
        ListNode temp2 = null;
        while(cur.next!=null && cur.next.next!=null){  //只写cur.next.next!=null报空指针
            temp0 = cur.next;
            temp1 = cur.next.next;
            temp2 = cur.next.next.next;
            cur.next = temp1;
            temp1.next = temp0;
            temp0.next = temp2;
            cur = cur.next.next;
        }
        return head1.next;
    }
}

cur.next 为 null 然后调用 null 的成员 next 当然出错了。没有其它办法,老老实实地写整吧

Long num = null;

if(num == null) 不报错
if(num > 0) 报错

Java 之所以稳定,可能就是因为它弱智吧