?Travelers 2021-12-05 21:01 采纳率: 50%
浏览 11

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;
    }
}
  • 写回答

1条回答 默认 最新

  • 八米二康 2021-12-05 21:17
    关注

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

    Long num = null;

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

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

    评论

报告相同问题?

问题事件

  • 创建了问题 12月5日

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划