public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null) return false;
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}
定义一个ListNode:
public static class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}



