LinkedList addToTail()不起作用

时间:2014-02-27 02:54:35

标签: java algorithm linked-list singly-linked-list

我无法理解为什么添加到此LinkedList类的尾部不起作用,并且在输出中被忽略。

这是一个简单的Node类:

public class IntNode {

private int val;
private IntNode next;

public IntNode() {
    this.val = 0;
    IntNode next = null;
}

public IntNode(int val) {
    this.val = val;
    this.next = null;
}

public IntNode next() {
    return this.next;
}

public int getVal() {
    return this.val;
}

public void setNextNode(int val) {
    this.next = new IntNode(val);
}
public void setNextNode(IntNode a)
{
    this.next = new IntNode(a.getVal());
}

public void setVal(int val) {
    this.val = val;
}

public String toString() {
    StringBuffer buff = new StringBuffer();
    return toString(this, buff);
}

private String toString(IntNode node, StringBuffer buff) {
    if (node == null) {
        return buff.toString();
    }

    buff.append(node.val);
    if (node.next != null) {
        buff.append(", ");
    } else {
        buff.append(".");
    }

    return toString(node.next(), buff);
}

}

这是链接列表:

public class LinkedList {

private IntNode header;
private IntNode trailer;
private int listSize;

public LinkedList()
{
    this.header = null;
    this.trailer = null;
    this.listSize = 0;
}
public LinkedList(IntNode a, IntNode b)
{
    this.header = a;
    this.trailer = b;
    this.header.setNextNode(this.trailer);
    this.listSize = 2;
}
public void addNode(IntNode a)
{
    this.trailer.setNextNode(a.getVal());
    this.trailer = this.trailer.next();
    this.listSize++;
}
public String toString()
{
    return this.header.toString();
}
public static void main(String args[])
{
    LinkedList lst = new LinkedList(new IntNode(1), new IntNode(2));
    lst.addNode(new IntNode(3));
    lst.addNode(new IntNode(4));
    System.out.println(lst.toString());
}

}

主要方法的输出是:1,2。 为什么添加方法不起作用?

3 个答案:

答案 0 :(得分:3)

在包含两个IntNode的构造函数中,您的header未指向trailer。相反,它指向new IntNode(trailer.val)。你应该改变

public void setNextNode(IntNode a)
{
    this.next = a;
}

答案 1 :(得分:2)

你的问题是LinkedList构造函数将header设置为a并挂载到b,但随后调用header.setNextNode(this.trailer);

IntNode的方法setNextNode()方法丢弃它传递的节点,而是创建一个与传入的节点具有相同值的节点。

这意味着在LinkedList构造函数的末尾,您将头部分配给a,其下一个节点值不是b,其值与b相同,而预告片设置为b。

您应该更改setNextNode()方法,不要丢弃它所传递的节点,如下所示:

public void setNextNode(IntNode a) {
    this.next = a;
}

答案 2 :(得分:2)

在LinkedList类的构造函数中,您拥有代码this.header.setNextNode(this.trailer);。这不会将头部的下一个节点设置为预告片,而是将头部的下一个节点设置为具有预告片值的另一个节点。设置预告片的下一个节点后,头部不受影响。