Skip to main content

Write a linked list program in java to add elements from the end of the list

 /**
 * Write a linked list program in java to add elements from the end of the list
   */
class Node
{
    int data;
    Node link;
    Node()
    {
        data=0;
        link=null;
    }
    void addEnd(int data)
    {
        Node temp = new Node();
        temp.data=data;
        if(this.link==null && this.data==0) 
        { //if the entire linked list is empty
            this.data=data;
        }
        else
        {
            Node ptr=this;
            while(ptr.link!=null)
            {
                ptr=ptr.link;
            }
            ptr.link=temp;
        }
        temp=null;
    }
    void display()
    {
        System.out.println("The elements are: ");
        Node ptr=this;
        while(ptr.link!=null){
            System.out.println(ptr.data);
            ptr=ptr.link;
        }
        System.out.println(ptr.data);
    }
    public static void main(String args[])
    {
        Node ob = new Node();
        ob.addEnd(50);
        ob.addEnd(80);
        ob.addEnd(90);
        ob.addEnd(100);
        ob.addEnd(110);
        ob.display();
    }
}

Popular posts from this blog