import java.util.*; /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { //有环,a和b都在head,a一次走一个,b一次走两个 //b!=null和b.next!=null就一直走(有环的模板) public boolean hasCycle(ListNode head) { if(head == null) return false; ListNode a = head, b = head; //可以理解为b.next.next,b.next不能为空。而b.next,则b不能为空 //由于连续走两下,所以b可能会为空 while(b != null && b.next != null){ a = a.next; b = b.next.next; if(a == b) return true; } return false; } }