Cycle Detection

/**
 * A LinkedList based solution for Detect a Cycle in a list
 * https://en.wikipedia.org/wiki/Cycle_detection
 */

function main () {
  /*
  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

  while (fast != null && fast.next != null && slow != null) {
    fast = fast.next.next
    slow = slow.next
    if (fast === slow) {
      return true
    }
  }
  return false
}

main()
Algerlogo

Β© Alger 2022

About us

We are a group of programmers helping each other build new things, whether it be writing complex encryption programs, or simple ciphers. Our goal is to work together to document and model beautiful, helpful and interesting algorithms using code. We are an open-source community - anyone can contribute. We check each other's work, communicate and collaborate to solve problems. We strive to be welcoming, respectful, yet make sure that our code follows the latest programming guidelines.