/**
* 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||head.next==null)return false;
ListNode node1=head;
ListNode node2=head;
//如果不成环,跳出循环
while(node2!=null&&node2.next!=null){
//确保可以追上
node1=node1.next;
node2=node2.next.next;
if(node1==node2)return true;
}
return false;
}
}

京公网安备 11010502036488号