以下是正确代码:
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&& 即可。