package com.zerroi.leetcode.Three22; public class HasCycle { public static void main(String[] args) { ListNode l1 = new ListNode(1); ListNode l2 = new ListNode(1); l1.next = l2; SolutionThird solutionThird = new SolutionThird(); boolean res = solutionThird.hasCycle(l1); System.out.println("res = " + res); } } class SolutionThird { public boolean hasCycle(ListNode head) { if (head.next == null) return false; ListNode slow = head; ListNode fast = head; while (fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { return true; } } return false; } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }