https://leetcode-cn.com/problems/linked-list-cycle-ii/
快慢指针
- 快指针一次走两步, 慢指针一次走一步
第一次相遇时,快指针回到原点,慢指针不动,接下来快指针也变成每次走一步,然后继续, 再次相遇就是第一个入环的节点
public ListNode detectCycle(ListNode head) {if (head == null || head.next == null || head.next.next == null) {return null;}ListNode slow = head.next;ListNode fast = slow.next;while (slow != fast) {if (fast.next == null || fast.next.next == null) {return null;}fast = fast.next.next;slow = slow.next;}fast = head;while (slow != fast ) {fast = fast.next;slow = slow.next;}return slow;}
