快指针一次走两个节点,慢指针一次走一个节点。我们只需要明白:如果其中一个指针可以到达尾节点,那么这个链表一定没有环。因为有环的节点是没有出口的,那么快慢指针在环中一定会相遇,也就是说只要slow和fast相等,就说明链表有环。
/**
* 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 slow = head;
ListNode fast = head;
while(slow != null && fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast) return true;
}
return false;
}
} 
京公网安备 11010502036488号