Program to detect a Loop in a Linked List

Please write your own version of program in the comment section below in different languages. Best answer will be uploaded on the website page once, the page is ready

One comment on “Program to detect a Loop in a Linked List”


  • Zubair

    package com.company;

    import java.io.*;
    import java.lang.*;
    import java.util.*;

    public class Main {
    public static void main(String[] args) {
    abc list1 = new abc();
    list1.insert(2);
    list1.insert(3);
    list1.insert(4);
    list1.insert(5);
    list1.head.next.next.next.next= list1.head;
    if (list1.checkdetection(list1.head)){
    System.out.println(true);
    }
    else {
    System.out.println(false);
    }

    }
    }
    class node{
    int data;
    node next;

    public node(int data) {
    this.data = data;
    this.next=null;
    }
    }
    class abc{
    public node head =null;
    public node tail =null;
    public void insert(int data ){
    node newnode =new node(data);
    if (head==null){
    head =newnode;
    tail=newnode;
    }
    else {
    tail.next=newnode;
    tail=newnode;
    }
    }
    public void display(node node ){
    if (node==null){
    return;
    }
    while (node!=null){
    System.out.print(node.data+” “);
    node=node.next;
    }
    System.out.println();

    }
    public boolean checkdetection(node head){
    node p=head;
    node q=head;
    while (p!=null&&q!=null &&q.next!=null){
    p=p.next;
    q=q.next.next;
    if (p==q){
    return true;
    }
    }
    return false;
    }
    }