判断链表是否有环时的空指针报错

以下是正确代码:

package day24;

/**
 * @auther Dawn
 * @create 2021-04-27 22:19
 **
 * 判断一个链表是否有环
 **/
public class Work2 {
    public static void main(String[] args) throws NullPointerException {
        Node1 n5 = new Node1("n5");
        Node1 n4 = new Node1("n4",n5);
        Node1 n3 = new Node1("n3",n4);
        Node1 n2 = new Node1("n2",n3);
        Node1 n1 = new Node1("n1",n2);
        //n5.next = n5;
       // print(n1);

        Node1 q = n1;
        Node1 s = n1;
        outer:
        while(true){
            for(int i = 0; i<100;i++) {
                while (q.next!=null&&q.next.next!=null&&s.next!=null) {
                    q = q.next.next;
                    s = s.next;
                    if (s.next == q.next) {
                        System.out.println("链表有环");
                        break outer;
                    }
                }
            }
            System.out.println("链表无环");
            break outer ;
        }

       // System.out.println("中间元素是:"+s.getData());





    }
    public static void print(Node current){
        if(current == null){
            return;
        }
        System.out.println(current.getData());
        print(current.getNext());
    }

}

 class Node1  {
    String value;
    Node1 next;

    public Node1(String value,Node1 next){
        this.value = value;
        this.next = next;
    }
    public Node1 getNext(){
        return next;
    }
    public String getData(){
        return value;
    }
     public Node1(String value){
         this.value = value;
     }
}

错误代码:
在这里插入图片描述
在while循环中加入判断:q.next!=null&& 即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值