解题思路:声明两个指针,快指针一次走两步,慢指针一次走一步
最后的结论是:有环的话两个指针一定会相遇,且相遇点到环口的距离=起点到环口的距离
时间复杂度为O(n),空间复杂度为O(1)
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
}