Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA Linked List, How do I insert a node at the end of the linked list, by trans

ID: 3788216 • Letter: J

Question

JAVA Linked List, How do I insert a node at the end of the linked list, by transversing the list

my constructor is here

public LLDogNode (Dog dog, LLDogNode link) {

this.contents = dog;

this.link = link;

}

now i have to implement this method to add an element called newnode2 at the end of the list, in this method, here is my attempt, I don't know what to do

public void insertTail(Dog dog) {

// put a new node containing dog at the tail of the list

LLDogNode newnode2 = new LLDogNode(dog, null);

if(head == null ){

head = newnode2;

}

else{

while(newnode2.getlink() != null){

newnode2 = newnode2.getLink();

}

newnode2 = newnode2.setlink(tail);

}

}

Explanation / Answer

Hi, Please find my implementation.

Please let me know in case of any issue.


public void insertTail(Dog dog) {

   // put a new node containing dog at the tail of the list
   LLDogNode newnode2 = new LLDogNode(dog, null);

   if(head == null ){
       head = newnode2;
   }
   else{

       LLDogNode temp = head;

       while(temp.getlink() != null){
           temp = temp.getLink();
       }

       temp.setlink(newnode2);
   }
}