Quick actions

cmd+k|ctrl+k

Navigation

Languages

Circular linked list validator

Snippet info

Language

Java

Visibility

public

Author

sivaram.krishna.3950

Created

2023-01-25T17:14:12.288222Z

Updated

2023-01-25T17:16:32.938943Z

//if the linkedlist is a circular linkedlist, first element appears itself again when the circle starts again.
//if it is not, the linkedlist ends with null

import java.util.*;
//node class for int data;
class node{
    node next;
    int data;
    public node(int d){
        data=d;
    }
}


//linkedlist class for creating a linkedlist, adding elements and validating for circular linkedlist
class list{
    node h;
    public void add(){
    h = new node(10);
    node n=h;
    n.next = new node(20);
    n=n.next;
    n.next = new node(30);
    n=n.next;
    n.next = new node(40);
    n=n.next;
    n.next = new node(50);
    n=n.next;
    n.next = new node(60);
    n=n.next;
    n.next = new node(70);
    n=n.next;
    n.next = new node(80);
    n=n.next;
    n.next = new node(90);
    n=n.next;
    
    //for creating circular linkedlist
    //n.next=h;
    
    //*for checking the entered values
    /*
    node t =h;
    for (int i=0;i<10;i++){
        System.out.println("i="+i+", data="+t.data);
        t=t.next;
    }*/
    }
    
    //validator to check for circular linkedlist
    public boolean validator(){
        if (h==null || h.next==null){
            return false;
        }
        node n=h.next;
        while (n.next!=null){
            if (n==h){
                return true;
            }n=n.next;
        }
        return false;
    }
    
}
class Main
{
	public static void main(String[] args) {
	    list l=new list();
	    l.add();
	    
		System.out.println(l.validator());
	}
}
INFO