Stack Bash - Master data structures and algorithms

Detect a cycle

Medium
Let's say you're given a singly linked list.
Write a function that determines if it has a cycle.
A cycle implies that the list has a loop, where a node points to a previous node in the list.
Here's an example of a singly linked list without a cycle, where Node 5 has no next node:
Linked List
And here's a linked list with a cycle:
Linked List with Cycle
Note how Node 5 points back to Node 3.

Try it first

Solution

8 Essential Linked Lists Coding Interview Problems

Master Linked Lists by trying the coding challenges below.
  1. 1.Insert NodeEasy
  2. 2.Remove NodeEasy
  3. 3.Find the MiddleEasy
  4. 4.Add Linked ListsEasy
  5. 5.Reverse Linked ListMedium
  6. 6.Detect CycleMedium
  7. 7.Merge Linked ListsMedium
  8. 8.Pivot Linked ListHard

Want to confidently pass your next coding interview?

Stack Bash helps new and veteran software engineers master data structures and algorithms for technical interviews.