알고리즘, 자료구조

[알고리즘] Leetcode. Linked List Cycle II

Alexim 2022. 7. 31. 14:58

Given the head of 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 (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

Do not modify the linked list.

 

var detectCycle = function(head) {
    if (!head || !head.next) return null;

    let slow = head;
    let fast = head;

    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;

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

Floyd's Cycle 알고리즘을 이용해서 cycle이 있는지 확인한 후 slow에는 head 값을 넣어주고 slow, fast를 한 칸씩 이동하다 만나는 지점이 loop의 시작지점이 된다.

 

출처 : https://www.youtube.com/watch?v=LUm2ABqAs1w&t=68s