快慢指针 02

92 阅读1分钟

LeetCode 142

leetcode-cn.com/problems/li…

题解

leetcode-cn.com/problems/li…

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            // 有环,开始找环的入口
            if (slow == fast) {
                while (slow != head) {
                    head = head.next;
                    slow = slow.next;
                }
                return slow;
            }
            
        }
        return null;
    }
}