Frage

I've been working on the exercise to better understand Linked List.

My output is:
***DISPALY NAMES Miki null Arek null Magi null


Problem: display nulls between names.

Tried to do: Wrote bunch of print statements and it looks like is adding extra Name reference object to the list. I was trying to find error in the add method but logically everything fines for me.

I am not allowed to use LinkedList API.

Thank you for your help.

<pre> <code>
public class NameTest {

public static void main(String[] args) {
    NameList<Name> n = new NameList<Name>();
    Name n1 = new Name(1,"Miki");
    Name n2 = new Name(2, "Arek");
    Name n3 = new Name(3, "Magi");

    n.addName(n1);
            n.addName(n2);
            n.addName(n3);
    n.displayNames();
    System.out.println("*******************\n");
     }
}

public class Name {

private int nameId;
private String firstName;   
private Name next;

public Name() { }

public Name(int nameId, String firstName) {
    super();
    this.nameId = nameId;
    this.firstName = firstName;
    this.next = new Name();
}

public int getNameId() {
    return nameId;
}

public void setNameId(int nameId) {
    this.nameId = nameId;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public Name getNext() {
    return next;
}

public void setNext(Name next) {
    this.next = next;
}   
}

public class NameList<T extends Name> {

private T head;
private int value;

public NameList() {
    head = null;
    value = 0;
}

public T getHead() {
    return head;
}

public void setHead(T head) {
    this.head = head;
}

public void addName(T name) { 
    if(head == null) {
        setHead(name);
        value++;
    }
    else {      
        T curr = getHead();
        while(curr.getNext() != null) {
            curr = (T) curr.getNext();
        }
        curr.setNext(name);
        value++;
    }
}

public void displayNames() {
    System.out.println("***DISPLAY NAMES ");
    T curr = getHead();

    while(curr.getNext() != null ) {
        System.out.println(curr.getFirstName());
        curr = (T) curr.getNext();
    }
    if(curr.getNext() == null) {
        System.out.println(curr.getFirstName());
    }
}

Instance variable next in the class name should be like this: private Name next; I am sorry for confusion. I made correction in the code above.

War es hilfreich?

Lösung

Your problem is this line.

this.next = new Name();

You're adding a new "empty object" onto the back of every Name that you add. Remove it and you'll get the desired result. (I assume you also have Name extends Employee in there somewhere, otherwise this doesn't compile).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top