Linked Lists: Detect a Cycle


Problem Statement :


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 5  points back to node 3.


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, head  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


0   <=  list size  <=  100



Solution :



title-img




                        Solution in C++ :

In  C++  :






/*


A Node is defined as: 
    struct Node {
        int data;
        Node* next;
    }
*/

#include <unordered_set>

std::unordered_set<Node*> visited;

bool has_cycle(Node* head)
{
    // Empty lists don't have circles.
    if(head == nullptr) {
        visited.clear();
        
        return false;
    }
    
    // If already in the list of visited nodes.
    if(visited.count(head) != 0) {
        visited.clear();
        
        // It means we have a cycle.
        return true;
    }
    
    // Otherwise, remember it.
    visited.insert(head);
    
    // Recurse for the rest of the list.
    return has_cycle(head->next);
}
                    


                        Solution in Java :

In   Java :






/*


A Node is defined as: 
    class Node {
        int data;
        Node next;
    }
*/

boolean hasCycle(Node head) {
    
    
    if(head==null)
        return false;
    else{
        Node slow=head;
        Node fast=head.next;
        while(fast!=null && fast.next!=null && fast!=slow){
            slow=slow.next;
            fast=fast.next.next;
        }
        if( fast!=null && fast==slow)
            return true;
        return false;
    }    

}
                    


                        Solution in Python : 
                            
In   Python3  :






"""


A Node is defined as: 
 
    class Node(object):
        def __init__(self, data = None, next_node = None):
            self.data = data
            self.next = next_node
"""


def has_cycle(head):
    visited = set()
    it = head
    while it.next:
        it = it.next
        if it in visited:
            return True
        visited.add(it)
    return False
                    


View More Similar Problems

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →