Refactor Cycledetection.js and added it's test. (#1099)

This commit is contained in:
Kartik Kapgate
2022-09-15 12:22:44 +05:30
committed by GitHub
parent d1152144aa
commit cf0593f430
2 changed files with 39 additions and 16 deletions

View File

@ -1,32 +1,24 @@
/**
* A LinkedList based solution for Detect a Cycle in a list
* A LinkedList based solution for Detecting a Cycle in a list.
* https://en.wikipedia.org/wiki/Cycle_detection
*/
function main () {
function detectCycle (head) {
/*
Problem Statement:
Given head, the head of a linked list, determine if the linked list has a cycle in it.
Note:
* While Solving the problem in given link below, don't use main() function.
* Just use only the code inside main() function.
* The purpose of using main() function here is to avoid global variables.
Link for the Problem: https://leetcode.com/problems/linked-list-cycle/
*/
const head = '' // Reference to head is given in the problem. So please ignore this line
let fast = head
let slow = head
if (!head) { return false }
while (fast != null && fast.next != null && slow != null) {
let slow = head
let fast = head.next
while (fast && fast.next) {
if (fast === slow) { return true }
fast = fast.next.next
slow = slow.next
if (fast === slow) {
return true
}
}
return false
}
main()
export { detectCycle }