代码实现:
public Node detectCycle() {
Node fast = this.head;
Node slow = this.head;
//判断是否有环,若有环则fast = slow,退出循环
while (fast != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
//每一次变化,都需要进行判断
if (fast == slow) {
break;
}
}
//若无环返回空
if (fast == null || fast.next == null) {
return null;
}
slow = this.head;
//当fast和slow没相遇时,fast和slow同时往后移
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return slow;
}