while(fast.next != null && fast.next.next != null) 如果交换了位置为while( fast.next.next != null&&fast.next != null)会出错。因为这种写法默认了fast.next不为null,如果恰好fast.next为空则fast.next.next会编译错误报错。
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null){//如果结点为空或者只有一个节点,false
return false;
}
ListNode slow = head;//慢指针
ListNode fast = head;//快指针
while(fast.next != null && fast.next.next != null){//要有两个判断条件,如果fast.next为空则短路不执行后半部分。。如果交换位置先判断fast.next.next如果fast后没节点会编译错误,因为null.next错
fast = fast.next.next;//快指针走两步
slow = slow.next;//慢走一步
if(slow == fast){//快指针在环这里循环了
return true;
}
}
return false;
}
}