LeetCode/com/zerroi/leetcode/Three22/HasCycle.java

38 lines
875 B
Java
Raw Normal View History

2024-03-25 20:14:01 +08:00
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;
}
}