题目
思路
- 涉及环相关的都会考虑使用快慢指针来解决。
- 通过快慢指针,如果它们相等,则说明存在环,出现null的,肯定不存在环。
- 通常来说快指针都是慢指针的速度的两倍
- 找到环起点如图所示
代码
public ListNode detectCycle(ListNode head) {if (head == null || head.next == null) return null;ListNode slow = head.next, fast = head.next.next;while (fast != null && fast.next != null) {if (slow.equals(fast)) break;slow = slow.next;fast = fast.next.next;}if (fast == null || fast.next == null) return null;while (!head.equals(slow)) {head = head.next;slow = slow.next;}return slow;}

