定义双指针,一个快,每次跳2步,一个慢,每次跳1步,只要有环,可以一直跳,快指针一定会有等于慢指针的时候。如果没有环,快指针一定会先到链表末尾,末尾是null,跳出循环。
/**
* 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) {
if(head == null)return false;
ListNode slow = head;
ListNode fast = head;
while(fast!= null && fast.next !=null){
slow = slow.next;
fast = fast.next.next;
if(slow==fast){
return true;
}
}
return false;
}
}