添加和打印链接列表时出错

时间:2016-10-19 12:48:25

标签: java linked-list

简单地说,我希望我的代码将给定的元素添加到列表中并将其打印到屏幕上。问题是,它打印列表的最后一个元素3次,而不打印其他元素。我花了很多时间,但我找不到问题。

public class Book {

private String name;
private double price;
private String writer;

public Book(String name, double price, String writer) {
    super();
    this.name = name;
    this.price = price;
    this.writer = writer;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}
public String getWriter() {
    return writer;
}
public void setWriter(String writer) {
    this.writer = writer;
}
}

这是Node类:

public class Node {

public static void main(String[] args) {

    Node nd = new Node(bk);
    Book bk1;
    bk1 = new Book("Of Mice and Men", 22, "John Steinbeck");
    nd.add(bk1);

    bk1 = new Book("The Grapes of Wrath", 28, "John Steinbeck");
    nd.add(bk1);

    bk1 = new Book("Tortilla Flat", 33, "John Steinbeck");
    nd.add(bk1);

    nd.printData();

}

private static Book bk;
private Node link;
public Node root;


public Book getBk() {
    return bk;
}
public void setBk(Book bk) {
    this.bk = bk;
}
public Node getLink() {
    return link;
}
public void setMyNode(Node link) {
    this.link = link;
}

public Node(Book bk) {
    super();
    this.bk = bk;
    this.link=null;
    this.root=null;

}

public void add(Book bk) {
    Node currentNode = root;
    Node newNode = new Node(bk);
    if(root==null){

        root = newNode;
    }
    else{
    while(currentNode.link!=null){

        currentNode = currentNode.link;

    }
    currentNode.link = newNode;
}
}

public void printData() {
    Node currentNode = root;

    while(currentNode!=null){
        Book bk = currentNode.getBk();
        System.out.println("Name: " + bk.getName() + " Price: " + bk.getPrice() + " Writer: " + bk.getWriter());
        currentNode =currentNode.link;
    }
}


}

2 个答案:

答案 0 :(得分:2)

您的节点类还需要Book实例变量:

private static Book bk;
private Book book;
private Node link;
public Node root;

然后需要更新这些方法以在类变量上使用实例变量:

public Book getBk() {
    return book;
}
public void setBk(Book bk) {
    this.book = bk;
}
public Node(Book bk) {
    super();
    this.book = bk;
    this.link=null;
    this.root=null;

}

我测试了这个并且它有效。

希望这有帮助,

利安

答案 1 :(得分:0)

使用三本不同的图书而不只是一张bk1