给定一个单链表,判断其是否带环 可以使用快慢指针的方式进行判断,让快指针一次走两步,慢指针一次走一步,若链表带环,则它们总会相遇,若不带环,则它们是不会相遇的。 代码实现:
class Node {
public int data
;
public Node next
;
public Node(int data
) {
this.data
= data
;
}
public Node() {
}
}
class LinkList {
Node head
= new Node();
public boolean hasCircle() {
Node fast
= this.head
;
Node slow
= this.head
;
while (fast
!= null
&& fast
.next
!= null
) {
fast
= fast
.next
.next
;
slow
= slow
.next
;
if (fast
== slow
) {
return true;
}
}
return false;
}
}
转载请注明原文地址: https://mac.8miu.com/read-515110.html