https://leetcode-cn.com/problems/linked-list-cycle/solution/
快慢指针
public boolean hasCycle(ListNode head) {if (head == null) {return false;}ListNode fast = head.next;ListNode slow = head;while (fast != slow) {if (fast == null || fast.next == null) {return false;}fast = fast.next.next;slow = slow.next;}return true;}
若还要你返回第一个入环的节点的话,那就在它们相遇时,slow停在原地, fast回到原点,变成两个都一次走一步,那么它俩一定会在第一个入环节点相遇
public ListNode getFirstLoopNode(ListNode head) {if (head == null || head.next == null || head.next.next == null) {return null;}ListNode fast = head.next;ListNode slow = head;while (fast != slow) {if (fast == null || fast.next == null) {return null;}fast = fast.next.next;slow = slow.next;}fast = head;while (slow != fast) {slow = slow.next;fast = fast.next;}return slow;}
