如果是环,两个速度不一样的数一定会在循环中相遇
public class S_141 {
public class Solution {
public boolean hasCycle(ListNode head) {
// 判断是否是空的
if(head == null||head.next == null){
return false;
}
// 建立两个步进速度不同的变量
ListNode fast = head;
ListNode slow = head;
// 在保证当前和下一个都有值的时候
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
// 快的和慢的相遇代表是一个环
if(slow == fast){
return true;
}
}
return false;
}
}
}