Java Program to create and display a singly linked list

 public class SandeepLinkedList {

    class Node{
        int data;
        Node next;

        public Node(int data){
            this.data=data;
            this.next=null;
        }
    }
    public Node head=null;
    public Node tail=null;

    public void addNode(int data){
        Node newNode=new Node(data);
        if(head==null){
            head=newNode;
            tail=newNode;
        }
        else{
            tail.next=newNode;
            tail=newNode;
        }
    }
   

       
    
    public void display(){
        Node current=head;
        if(head==null){
            System.out.println("list is empty");
            return;
        }
        System.out.println("Node of singly linked list");
        while(current !=null){
            System.out.println(current.data+" ");
            current=current.next;
        }
        System.out.println();
    
    }
    public static void main(String[] args){
        SandeepLinkedList Slist=new SandeepLinkedList();
        Slist.addNode(1);
        Slist.addNode(2);
        Slist.addNode(3);
        Slist.addNode(4);
        Slist.addNode(5);
    
    Slist.display();

    }
}
output: Node of singly linked list:
1 2 3 4 5

Comments