diff --git a/DIRECTORY.md b/DIRECTORY.md index 7920c4517a..d24e1ec266 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -61,6 +61,7 @@ * [MinPriorityQueue](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Heap/MinPriorityQueue.js) * Linked-List * [CycleDetection](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/CycleDetection.js) + * [CycleNode](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/CycleNode.js) * [DoublyLinkedList](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/DoublyLinkedList.js) * [RotateListRight](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/RotateListRight.js) * [SingleCircularLinkedList](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Linked-List/SingleCircularLinkedList.js.js) diff --git a/Data-Structures/Linked-List/CycleNode.js b/Data-Structures/Linked-List/CycleNode.js new file mode 100644 index 0000000000..d480eddffe --- /dev/null +++ b/Data-Structures/Linked-List/CycleNode.js @@ -0,0 +1,42 @@ +/* + Problem: Given a linked list, return the node where cycle begins. If there is no cycle return null + + Approach used: Floyd Cycle Detection Algorithm + + What is Floyd Cycle Detection Algorithm? + - Floyd Cyclce Detection algorithm uses two pointer (slow & fast), in which fast pointer move twice the speed of slow pointer. + - It is also known as hare and tortoise algorithm as we can imagine slow pointer as tortoise that moves slow and hare as the fast one. + - If the fast pointer reaches null, that means there was no cycle. + - If the fast pointer and slow pointer becomes equal that means there was cycle. + + For reference: https://www.codingninjas.com/blog/2020/09/09/floyds-cycle-detection-algorithm/ +*/ + +/* + Input: Pass the head (first node) of linked list +*/ +const detectCycleNode = (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) break + } + + slow = head + + while (fast && slow !== fast) { + slow = slow.next + fast = fast.next + } + + return fast +} + +export { detectCycleNode }

AltStyle によって変換されたページ (->オリジナル) /