142. Linked List Cycle II

1. Description

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.

2. Example

Example 1:
Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 1

Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 2

Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
Example 3

3. Constraints

  • The number of the nodes in the list is in the range [0, $10^4$].
  • $-10^5$ <= Node.val <= $10^5$
  • pos is -1 or a valid index in the linked-list.

4. Follow Up

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

5. Solutions

My Accepted Solution(Follow Up)

n is the number of nodes in m_head
Time complexity: O(n)
Space complexity: O(1)

explain

class Solution {
public:
    // ListNode *detectCycle(ListNode *head)
    ListNode *detectCycle(ListNode *i_head) {
        // slow moves one step every time, fast moves two steps every time
        auto slow = i_head, fast = i_head;
        while (fast) {  // if the fast faces nullptr, there is no loop
            slow = slow->next;
            if (!fast->next) {  // if the fast faces nullptr, there is no loop
                return nullptr;
            }
            fast = fast->next->next;

            if (slow == fast) {
                auto iter = i_head;
                while (iter != slow) {
                    slow = slow->next;
                    iter = iter->next;
                }

                return iter;
            }
        }

        return nullptr;
    }
};
comments powered by Disqus