DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Detect Cycle LinkedList - II

We have 2 step process
1) check if cycle exists?
2) if exist get that node

var detectCycle = function(head) {
    let meetingNode = getMeetingNode(head);

    if(meetingNode !== null){
        let start = head;
        let cycleAt = meetingNode;

        while(start != meetingNode){
            start = start.next;
            meetingNode= meetingNode.next;
        }
        return start;
    }
    return meetingNode;

};
var getMeetingNode = function(head) {
    let slow = head;
    let fast =  head;
    while(fast !== null && fast.next !== null){
        slow = slow?.next;
        fast = fast?.next?.next;

         if(slow == fast){
            return slow;
        }
    }
    return null;
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)