Given a singly linked list, check if the linked list has a loop (cycle) or not. A loop means that the last node of the linked list is connected back to a node in the same list.
[Naive Approach] Using HashSet - O(n) Time and O(n) Space
The idea is to insert the nodes in the Hashset while traversing and whenever a node is encountered that is already present in the hashset (which indicates there's a cycle (loop) in the list) then return true. If the node is NULL, represents the end of Linked List, return false as there is no loop.
C++
// C++ program to detect loop in a linked list// using hashset#include<iostream>#include<unordered_set>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){this->data=x;this->next=nullptr;}};booldetectLoop(Node*head){unordered_set<Node*>st;while(head!=nullptr){// If this node is already present// in hashmap it means there is a cycleif(st.find(head)!=st.end())returntrue;// If we are seeing the node for// the first time, insert it in hashst.insert(head);head=head->next;}returnfalse;}intmain(){// Create a hard-coded linked list:// 1 -> 3-> 4Node*head=newNode(1);head->next=newNode(3);head->next->next=newNode(4);// Create a loophead->next->next->next=head->next;if(detectLoop(head))cout<<"true";elsecout<<"false";return0;}
Java
// Java program to detect loop in a linked list// using hashsetimportjava.util.HashSet;classNode{intdata;Nodenext;Node(intx){this.data=x;this.next=null;}}classGfG{staticbooleandetectLoop(Nodehead){HashSet<Node>st=newHashSet<>();while(head!=null){// If this node is already present// in hashmap it means there is a cycleif(st.contains(head))returntrue;// If we are seeing the node for// the first time, insert it in hashst.add(head);head=head.next;}returnfalse;}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 3-> 4Nodehead=newNode(1);head.next=newNode(3);head.next.next=newNode(4);// Create a loophead.next.next.next=head.next;if(detectLoop(head))System.out.println("true");elseSystem.out.println("false");}}
Python
# Python program to detect loop in a linked list# using hashsetclassNode:def__init__(self,x):self.data=xself.next=NonedefdetectLoop(head):st=set()whileheadisnotNone:# If this node is already present# in hashmap it means there is a cycleifheadinst:returnTrue# If we are seeing the node for# the first time, insert it in hashst.add(head)head=head.nextreturnFalseif__name__=="__main__":# Create a hard-coded linked list:# 1 -> 3 -> 4head=Node(1)head.next=Node(3)head.next.next=Node(4)# Create a loophead.next.next.next=head.nextifdetectLoop(head):print("true")else:print("false")
C#
// C# program to detect loop in a linked list// using hashsetusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intx){this.data=x;this.next=null;}}classGfG{staticbooldetectLoop(Nodehead){HashSet<Node>st=newHashSet<Node>();while(head!=null){// If this node is already present// in hashmap it means there is a cycleif(st.Contains(head))returntrue;// If we are seeing the node for// the first time, insert it in hashst.Add(head);head=head.next;}returnfalse;}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 3 -> 4Nodehead=newNode(1);head.next=newNode(3);head.next.next=newNode(4);// Create a loophead.next.next.next=head.next;if(detectLoop(head))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// JavaScript program to detect loop in a linked list// using hashsetclassNode{constructor(x){this.data=x;this.next=null;}}functiondetectLoop(head){constst=newSet();while(head!==null){// If this node is already present// in hashmap it means there is a cycleif(st.has(head))returntrue;// If we are seeing the node for// the first time, insert it in hashst.add(head);head=head.next;}returnfalse;}// Driver Code// Create a hard-coded linked list:// 1 -> 3 -> 4lethead=newNode(1);head.next=newNode(3);head.next.next=newNode(4);// Create a loophead.next.next.next=head.next;if(detectLoop(head))console.log("true");elseconsole.log("false");
Output
true
Time complexity: O(n), where n is the number of nodes in the Linked List. Auxiliary Space: O(n), n is the space required to store the value in the hash set.
[Expected Approach] Using Floyd's Cycle-Finding Algorithm - O(n) Time and O(1) Space
This idea is to use Floyd's Cycle-Finding Algorithmto find a loop in a linked list. It uses two pointers slow and fast, fast pointer move two steps ahead and slow will move one step ahead at a time.
Follow the steps below to solve the problem:
Traverse linked list using two pointers.
Move one pointer(slow) by one step ahead and another pointer(fast) by two steps ahead.
If these pointers meet at the same node then there is a loop. If pointers do not meet then the linked list doesn't have a loop.
// C++ program to detect loop in a linked list// using Floyd's Cycle-Finding Algorithm#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){this->data=x;this->next=nullptr;}};booldetectLoop(Node*head){// Fast and slow pointers initially points to the headNode*slow=head,*fast=head;// Loop that runs while fast and slow pointer are not// nullptr and not equalwhile(slow&&fast&&fast->next){slow=slow->next;fast=fast->next->next;// If fast and slow pointer points to the same node,// then the cycle is detectedif(slow==fast){returntrue;}}returnfalse;}intmain(){// Create a hard-coded linked list:// 1 -> 3-> 4Node*head=newNode(1);head->next=newNode(3);head->next->next=newNode(4);// Create a loophead->next->next->next=head->next;if(detectLoop(head))cout<<"true";elsecout<<"false";return0;}
C
// C program to detect loop in a linked list// using Floyd's Cycle-Finding Algorithm#include<stdbool.h>#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};intdetectLoop(structNode*head){// Fast and slow pointers initially points to the headstructNode*slow=head,*fast=head;// Loop that runs while fast and slow pointer are not// nullptr and not equalwhile(slow&&fast&&fast->next){slow=slow->next;fast=fast->next->next;// If fast and slow pointer points to the same node,// then the cycle is detectedif(slow==fast){returntrue;}}returnfalse;}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}intmain(){// Create a hard-coded linked list:// 1 -> 3-> 4structNode*head=createNode(1);head->next=createNode(3);head->next->next=createNode(4);// Create a loophead->next->next->next=head->next;if(detectLoop(head))printf("true");elseprintf("false");return0;}
Java
// Java program to detect loop in a linked list// using Floyd's Cycle-Finding AlgorithmclassNode{intdata;Nodenext;publicNode(intx){this.data=x;this.next=null;}}classGfG{staticbooleandetectLoop(Nodehead){// Fast and slow pointers initially points to the headNodeslow=head,fast=head;// Loop that runs while fast and slow pointer are not// null and not equalwhile(slow!=null&&fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;// If fast and slow pointer points to the same node,// then the cycle is detectedif(slow==fast){returntrue;}}returnfalse;}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 3 -> 4Nodehead=newNode(1);head.next=newNode(3);head.next.next=newNode(4);// Create a loophead.next.next.next=head.next;if(detectLoop(head))System.out.println("true");elseSystem.out.println("false");}}
Python
# Python program to detect loop in a linked list# using Floyd's Cycle-Finding AlgorithmclassNode:def__init__(self,x):self.data=xself.next=NonedefdetectLoop(head):# Fast and slow pointers initially points to the headslow=headfast=head# Loop that runs while fast and slow pointer are not# None and not equalwhileslowandfastandfast.next:slow=slow.nextfast=fast.next.next# If fast and slow pointer points to the same node,# then the cycle is detectedifslow==fast:returnTruereturnFalseif__name__=="__main__":# Create a hard-coded linked list:# 1 -> 3 -> 4head=Node(1)head.next=Node(3)head.next.next=Node(4)# Create a loophead.next.next.next=head.nextifdetectLoop(head):print("true")else:print("false")
C#
// C# program to detect loop in a linked list// using Floyd's Cycle-Finding AlgorithmusingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){this.data=x;this.next=null;}}classGfG{staticbooldetectLoop(Nodehead){// Fast and slow pointers initially points to the headNodeslow=head,fast=head;// Loop that runs while fast and slow pointer are not// null and not equalwhile(slow!=null&&fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;// If fast and slow pointer points to the same node,// then the cycle is detectedif(slow==fast){returntrue;}}returnfalse;}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 3 -> 4Nodehead=newNode(1);head.next=newNode(3);head.next.next=newNode(4);// Create a loophead.next.next.next=head.next;if(detectLoop(head))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// JavaScript program to detect loop in a linked list// using Floyd's Cycle-Finding AlgorithmclassNode{constructor(x){this.data=x;this.next=null;}}functiondetectLoop(head){// Fast and slow pointers initially points to the headletslow=head,fast=head;// Loop that runs while fast and slow pointer are not// null and not equalwhile(slow&&fast&&fast.next){slow=slow.next;fast=fast.next.next;// If fast and slow pointer points to the same node,// then the cycle is detectedif(slow===fast){returntrue;}}returnfalse;}// Driver Code// Create a hard-coded linked list:// 1 -> 3 -> 4lethead=newNode(1);head.next=newNode(3);head.next.next=newNode(4);// Create a loophead.next.next.next=head.next;if(detectLoop(head))console.log("true");elseconsole.log("false");
Output
true
Time complexity: O(n), where n is the number of nodes in the Linked List. Auxiliary Space: O(1).
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.