Detect loop in a linked list

Generally in singly linked list last node pointer fields are contain NULL value. That NULL value indicate end of linked list.

If In a case this last node pointer fields are not NULL. So this last node next pointer fields are store the address of other node of linked list. Suppose that this pointer are storing the address of existing linked list node. In this situation linked list contain loop. So our goal are is to detecting loop in given single linked list.

Suppose we are inserted the following (1,2,3,4,5,6) node in a sequence.

Detect loop in linked list

Here given code implementation process.

//C Program to Detect loop in a linked list
#include<stdio.h>
#include <stdlib.h> //for malloc function

//create structure
struct Node{
  int data;
  struct Node*next;
};
//function prototype
void insert(struct Node**,int);
void display(struct Node*);
void detect_loop(struct Node*);
//insert Node element
void insert(struct Node**head,int value){
    //Create dynamic node
  struct Node*node=(struct Node*)malloc(sizeof(struct Node));
  if(node==NULL){
    printf("Memory overflow\n");
  }else{
    node->data=value;
    node->next=NULL;
    if(*head==NULL){
      *head=node;
    }else{
      struct Node*temp=*head;
      //find last node
      while(temp->next!=NULL){
        temp=temp->next;
      }
      //add node at last position
      temp->next=node;
    }
  }
}


void detect_loop(struct Node*head){
  if(head==NULL){
    printf("\n Empty Linked List");
  }
  int status=0;
  struct Node*first=head,*second=head;
  while(second!=NULL && second->next!=
    NULL && second->next->next != NULL){
    second=second->next->next; //increment by 2 node visit
    first=first->next; //visit to next node
    if(first==second){
      //found loop
      status=1;
      break;
    }
  }
  if(status==1){
    printf("Yes\n");
  }else{
    printf("No\n");
  }
  
}
int main(){
  //Create node pointer
  struct Node*head=NULL;

  //Insert element of linked list
  insert(&head,1);
  insert(&head,2);
  insert(&head,3);
  insert(&head,4);
  insert(&head,5);
  insert(&head,6);

  detect_loop(head);
  //set loop
  head->next->next->next->next->next->next=head->next;
  detect_loop(head);
  return 0;
}

Output

No
Yes
//C++ Program to Detect loop in a linked list

#include<iostream>
using namespace std;

//create structure
struct Node{
  int data;
  struct Node*next;
};
class LinkedList{
  
public:
  Node*head;
  LinkedList();
  void insert(int);
  void detect_loop();
};
//set head pointer value
LinkedList ::LinkedList(){
  head=NULL;
}
//insert Node element
void LinkedList:: insert(int value){
    //Create dynamic node
  Node*node=new Node;
  if(node==NULL){
    cout<<"Memory overflow"<<endl;
  }else{
    node->data=value;
    node->next=NULL;
    if(head==NULL){
      head=node;
    }else{
      Node*temp=head;
      //find last node
      while(temp->next!=NULL){
        temp=temp->next;
      }
      //add node at last possition
      temp->next=node;
    }
  }
}

//check loop is exist in this linked list
void LinkedList:: detect_loop(){
  if(head==NULL){
    cout<<"\n Empty Linked List";
  }
  int status=0;
  Node*first=head,*second=head;
  while(second!=NULL && second->next!=
    NULL && second->next->next != NULL){
    second=second->next->next; //increment by 2 node visit
    first=first->next; //visit to next node
    if(first==second){
      //found loop
      status=1;
      break;
    }
  }
  if(status==1){
    cout<<"Yes"<<endl;
  }else{
    cout<<"No"<<endl;
  }
}

int main(){
  LinkedList obj=LinkedList();
  //insert element of linked list
  obj.insert(1);
  obj.insert(2);
  obj.insert(3);
  obj.insert(4);
  obj.insert(5);
  obj.insert(6);
  obj.detect_loop();
  obj.head->next->next->next->next->next->next=obj.head->next;
  obj.detect_loop();
  return 0;
}

Output

No
Yes
//Java Program
//Detect loop in a linked list
class Node {
  public int data;
  public Node next;
  public Node(int value) {
    data = value;
    next = null;
  }
}
public class LinkedList {

  public Node head;
  //Class constructors
  LinkedList() {
    head = null;
  }
  //insert node at last of linke list
  public void insert(int value) {
    //Create a node
    Node node = new Node(value);

    if (head == null) head = node;
    else {
      Node temp = head;
      //find lase node
      while (temp.next != null) {
        temp = temp.next;
      }
      //add node
      temp.next = node;
    }

  }
  //Detecting loop of linked list
  public void detectLoop() {
    if (head == null) {
      System.out.println("Empty Linked List ");
    } else {
      int status = 0;
      Node first = head, second = head;
      while (second != null && second.next != null && second.next.next != null) {
        first = first.next;
        second = second.next.next;
        if (first == second) {
          //loop is found
          status = 1;
          break;
        }
      }
      if (status == 1) {

        System.out.println("Yes");

      } else {
        System.out.println("No");
      }

    }
  }


  public static void main(String[] args) {
    LinkedList obj = new LinkedList();
    obj.insert(1);
    obj.insert(2);
    obj.insert(3);
    obj.insert(4);
    obj.insert(5);
    obj.insert(6);
    obj.detectLoop();
    obj.head.next.next.next.next.next.next = obj.head.next;
    obj.detectLoop();

  }
}

Output

No
Yes
#Python program to 
#Detect loop in a linked list
class Node:
  def __init__(self,data):
    self.data=data
    self.next=None

#create class Linked    
class Linked:
    def __init__(self):
        #Assign default value
        self.head=None
    
    #insert new node to linked list  
    def insert(self,data):
        node=Node(data)
        node.next=None
        if self.head==None:
            self.head=node
        else:
            temp=self.head
            while temp.next!=None:
                temp=temp.next
            #add node    
            temp.next=node
     
    #find loop is exist or not    
    def detectLoop(self):
        first=self.head
        second=self.head
        status=0
        while second!=None and second.next!=None and second.next.next!=None:
            first=first.next
            second=second.next.next
            if(first==second):
                status=1
                break
        if(status==1):
           
            print("Yes")
        else:
            print("No")    
def main():
    #Create Object of class Linked
    obj=Linked()
    #Insert Linked Elements
    obj.insert(1);
    obj.insert(2);
    obj.insert(3);
    obj.insert(4);
    obj.insert(5);
    obj.insert(6);
    
    obj.detectLoop();
    #set loop
    obj.head.next.next.next.next.next.next = obj.head.next;

    obj.detectLoop();
    

if __name__=="__main__":
    main()

Output

No
Yes
//C# program to 
//Detect loop in a linked list
using System;
//node class
public class Node{
  public  int data;
  public  Node next;
}
class Program
{
  public Node head;
  public Program(){
    head=null;
  }
  //insert node of linked list
  public void insert(int data){
    Node newNode=new Node();
    newNode.data=data;
    newNode.next=null;
    if(head==null) head=newNode;
    else{
      Node temp=head;
      //get middle node
      while(temp.next!=null ){
        temp=temp.next;

      }
      //add new node

      temp.next=newNode;
    }
  }

  //check loop is exist or not
  public void detectLoop(){
    if(head==null){
      Console.Write("Empty Linked List ");
    }else{
      int status=0;
      Node first=head,second=head;
      while(second!=null && second.next!=null && second.next.next!=null){
        first=first.next;
        second=second.next.next;
        if(first==second){
          //loop is found
          status=1;
          break;
        }
      }
      if(status==1){
        
        Console.WriteLine("Yes");

      }else{
        Console.WriteLine("No");
      }

    }
  }

  static void Main(){

    Program obj=new Program();
    //insert element value
    obj.insert(1);
    obj.insert(2);
    obj.insert(3);
    obj.insert(4);
    obj.insert(5);
    obj.insert(6);
    obj.detectLoop();
    //set loop
    obj.head.next.next.next.next.next.next = obj.head.next;

    obj.detectLoop();
  }
}

Output

No
Yes
<?php
//Php program 
//Detect loop in a linked list
class Node
{
    public $data;
    public $next;
    function __construct($data)
    {
        $this->data = $data;
        $this->next = NULL;
    }
}
class LinkedList{

    public $head;
    function __construct()
    {
        $head=NULL;
    }
       /*
    * Append the Given data value at end of linked list
    * Fun : insert
    * Parm: data value
    *@return None
    */
    function insert($data)
    {
        $newNode=new Node($data); 
        if($this->head==NULL)
        {
            $this->head=$newNode;
        }else{
            $temp=$this->head;
            //find last node of linked list
            while($temp->next!=NULL){
                $temp=$temp->next;
            }
            //add new node to last of linked list
            $temp->next=$newNode;
        }
    }

    //check loop is exist in this linked list
    function detect_loop()
    {
      if($this->head==NULL)
      {
        echo"<br> Empty Linked List";
      }
      $status=0;
      $first=$this->head;
      $second=$this->head;
      
      while($second!=NULL && $second->next!=
        NULL && $second->next->next != NULL)
      {
        
        $second=$second->next->next; //increment by 2 node visit
       
        $first=$first->next; //visit to next node
        
        if($first==$second)
        {
          //found loop
          $status=1;
          break;
        }
      }
      if($status==1)
      {
        
        echo "Yes <br>";
      
      }
      else
      {
        echo"No <br>";
      }
    }
    //Display all inserted node in linked list
    function display()
    {
        if($this->head==NULL)
        {
            echo "Empty Linked List";
        }
        else
        {
            $temp=$this->head;
            echo "<br>Linked List :";
            while($temp!=NULL)
            {
                //display node value
                echo "&nbsp;&nbsp;".$temp->data;
                $temp=$temp->next; //visit to next node
            }
        }   
    }
}
function main(){
  //Make a object of LinkedList class
  $obj= new LinkedList();

  /*
  *Insert following nodes in linked list
  */
 
  $obj->insert(1);
  $obj->insert(2);
  $obj->insert(3);
  $obj->insert(4);
  $obj->insert(5);
  $obj->insert(6);
  $obj->detect_loop();
  $obj->head->next->next->next->next->next->next= $obj->head->next;
  $obj->detect_loop();
}
main();
?>

Output

No
Yes


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved