We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Hiring developers?
  1. Linked Lists: Detect a Cycle

Linked Lists: Detect a Cycle

Problem
Submissions
Leaderboard
Discussions
Editorial
Topics

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. For example, in the following graph there is a cycle formed when node points back to node .

image

Function Description

Complete the function has_cycle in the editor below. It must return a boolean true if the graph contains a cycle, or false.

has_cycle has the following parameter(s):

  • head: a pointer to a Node object that points to the head of a linked list.

Returns

  • boolean: True if there is a cycle, False if there is not

Note: If the list is empty, will be null.

Input Format

There is no input for this challenge. A random linked list is generated at runtime and passed to your function.

Constraints

Sample Input

The following linked lists are passed as arguments to your function:

image

image

Sample Output

0
1

Explanation

  1. The first list has no cycle, so we return false and the hidden code checker prints to stdout.
  2. The second list has a cycle, so we return true and the hidden code checker prints to stdout.

Author

harsha_s

Difficulty

Easy

Max Score

25

Submitted By

101352

Need Help?


View discussions
View editorial
View top submissions
RESOURCES

  • Linked Lists

rate this challenge

MORE DETAILS

Download problem statement
Download sample test cases
Suggest Edits
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy