Search code examples
hyperlinkinserteclipselinkinsertion

java insert at end linked list


my code for insert at the end was not working help me please how can i insert element at the end of the linked list in java linked list is really confusing ,, anyone please answer my question please before i got some other doubts nd got it cleared thanks frnds fr doing so please answer me again how insert element to the end of the list in my code

        import    java . util.Scanner;
    
    
    
    class node
    {
        int i,q;	
         node next;
         node prev;
    }
    
    class link{
        public static void main(String args[])
    {
        	linkk l = new linkk();
        	
      l.op();
        	int user=0;  	
         while(user!=10)
        {Scanner a=new Scanner(System.in);
          if(user==1)
          {
        	  System.out.println("\nenter data\n");
        	  
        	  l.create(a.nextInt());
         
          }System.out.println("\n1.create link\n2.insert beginning\n3.insert middle\n4.insert end\n5.delete data\n6.reverse");
    user=a.nextInt();
    }
    if(user==2)
    l.insertbeg();
    if(user==3)
    	l.insertmid();
    if(user==4)
    	l.insertend();
    if(user==5)
    	l.del();
    if(user==6)
    	l.reverse();
    if(user==7)
    l.display();
    		
    	}
    
    }
    
    class  linkk
    {  
    node temp4;
    int ch,add,cnt=0,t=0,b;
    node p= new node();
    node q;
    	node last;
    node first=new node;
    
    public boolean isEmpty()
    
    {
    
        return first == null;
    
    }
    
    public  void insertbeg()
    {
    }
    
    public  void insertmid()
    {
    }
    public void insertend()
    {//this is my code but not working

     p=new node();
	System.out.println("enter data"); 
	p.i=b.nextInt();
 	temp=first;
	while(temp.next!=null)
	temp=temp.next;
	temp.next=p;
	p.next=null;
cnt++;

    }
    public  void del()
    {
    } 
    public  void reverse()
    {
    }
    public  void display()
    {
    }
    public  void create(int val)
    {   
    	 first.i=val;
    
    	 first.next=null;
    	 cnt++;   
            }
     public void ob()
     {
     }
     public void op()
     {
    }
    }


Solution

  • You iterate until the last node and then add your new node with the last node's next pointer.

    Try something like:

    public void insertend(node newNode) {
        node nextNode = headNode;
        while (nextNode.next != null) {
            nextNode = nextNode.next;
        }
        nextNode.next = newNode;
    }