wupangyen / LeetCode

LeetCode
1 stars 0 forks source link

LeetCode 142. Linked List Cycle II #3

Open wupangyen opened 3 years ago

wupangyen commented 3 years ago

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.

Example : 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.

wupangyen commented 3 years ago

This is related to the question Linked List Cycle I

here we want to return the node where the cycle start.

first we want to check if the linked list have cycle or not, we can use the method we did in linked list cycle I

if there is no cycle we return null if there is cycle we return the node that where slow node and fast node intersect

after we find the intersect node

we can find the node that start the cycle first we assign slow node to head and fast node to the intersect node

the slow node and intersect node both move at the same pace

while slow node is not the same as intersect node

slow = slow.next intersect = intersect.next

after exit the loop means they are at the same node

we have found the node that start the cycle return slow

wupangyen commented 3 years ago

public class Solution { public ListNode detectCycle(ListNode head) {

    if(head == null || head.next == null){
        return null;
    }

    ListNode intersect = isCycle(head);
    if(intersect == null){
        return null;
    }

    ListNode slow = head;

    while(slow != intersect){

        slow = slow.next;
        intersect = intersect.next;
    }

    return slow;

}

public ListNode isCycle(ListNode head){

    ListNode slow = head;
    ListNode fast = head;

    while(fast != null && fast.next != null ){

        slow = slow.next;
        fast = fast.next.next;
        if(slow == fast){
            return slow;
        }

    }
    return null;
}

}

wupangyen commented 3 years ago

time O(n) space O(n)