Leetcode 142 Linked List Cycle II

Description

142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally,

pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.

Notice that you should not modify the linked list.

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

Solution

  1. 使用fast slow pointers,如果两个指针不能相遇 return null
  2. 如果两个指针相遇,相遇的位置为 C % F, C为环的结点个数,F为head到intersection point的结点个数
  3. 相遇后slow pointer退回到起始点,fast移动到下一个结点。之后fast slow pointers每次移动一个位置,两个指针再次相遇的位置即为intersection point

    public class Solution {
    //time complexity O(n) || space complexity O(1)
        public ListNode detectCycle(ListNode head) {
            if(head == null || head.next == null)
                return null;

            ListNode slow = head;
            ListNode fast = head.next;
            while(fast != null && fast.next != null){
                if(fast == slow){
                    slow = head;
                    fast = fast.next;
                    while(fast != slow){
                        fast = fast.next;
                        slow = slow.next;
                    }
                    return fast;
                }

                fast = fast.next.next;
                slow = slow.next;
            }
            
            return null;
        }
    }