public boolean hasCycle(ListNode head) {// 边界条件if (head == null || head.next == null) {return false;}// 慢指针 龟ListNode slow = head;// 快指针 兔ListNode fast = head.next;// 龟兔赛跑不相遇则继续跑,直到相遇while (slow != fast) {// 退出条件 跑到尽头if (fast == null || fast.next== null) {return false;}// 龟走一步slow = slow.next;// 兔子走两步fast = fast.next.next;}return true;}
public boolean hasCycle(ListNode head) {// 慢指针 龟ListNode slow = head;// 快指针 兔ListNode fast = head;// 跑到尽头才退出while (fast != null) {// 走一步slow = slow.next;if (fast.next != null) {// 走两步fast = fast.next.next;} else {// 跑到尽头才退出return false;}// 环路if (slow == fast) {return true;}}return false;}
public boolean hasCycle(ListNode head) {ListNode slow = head;ListNode fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;if (slow == fast) {return true;}}return false;}
public boolean hasCycle(ListNode head) {// 边界条件if (head == null || head.next == null) {return false;}HashSet<ListNode> set = new HashSet<ListNode>();while (head != null) {// 检查是否有重复添加if (!set.add(head)) {return true;}head = head.next;}return false;}
