Moj
Moj

Reputation: 11

Linked list addLast method

How can I build an addLast method in Java? I already know LinkedList has a built-in method which does this)

This is what I've tried:

public void addFirst(int d1, double d2) { 
    Link link = new Link(d1, d2); 
    link.nextLink = first; 
    first = link;
        }
public void addLast(int d1 , double d2){
    Link v = new Link(d1, d2);
    v.nextLink = null;
    tail.nextLink = v;
   tail = v  

}

    public void printList() { 
    Link currentLink = first; 
    System.out.print("List: "); 
    while(currentLink != null) { 
    currentLink.printlink(); 
    currentLink = currentLink.nextLink; 
    } 
        System.out.println(""); 
}

My addFirst method works, but I don't know how to connect them.

in the main :

    LinkList list = new LinkList();  
         list.addFirst(4, 4.04); 
         list.addFirst(5, 5.05); 
         list.addlast(3,4.5);
         list.printList();

Upvotes: 1

Views: 15754

Answers (3)

kin
kin

Reputation: 1

public void addLast(int d1, double d2){

    Node node = new Node(d1, d2);
    Node temp = first;
    while(temp.next!= null) {
        temp = temp.next;
    }
    temp.next = node;
}

Upvotes: 0

Woot4Moo
Woot4Moo

Reputation: 24316

I realize that this is a school assignment so without giving the answer here are the steps to follow:

  1. check if list is empty
  2. if list is empty set head + tail to point to same node
  3. Iterate over all elements
  4. Update tail to new node

Also there is no way that the addFirst method you have above would work you are constantly resetting the value in tail.

Upvotes: 3

pfhayes
pfhayes

Reputation: 3927

Your problem appears to be in the last line. You want

tail = v;

Not

v = tail;

Furthermore, You have

tail = link

as the last line of your addFirst method - it's not clear why you're doing this. You shouldn't need to update the tail of the list as you add to the front.

Upvotes: 1

Related Questions