【发布时间】:2014-03-30 06:24:12
【问题描述】:
我不明白为什么添加到这个 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());
}
}
main方法的输出是:1、2。 为什么添加方法不起作用?
【问题讨论】:
-
@SotiriosDelimanolis 没必要粗鲁。
-
@nachokk 我相信没关系——这是一种递归方法。
-
@mbroshi 我没注意返回部分 xD
-
一般来说,当你想复制你的函数参数时,你似乎需要重新考虑,而不是当你只想引用它们时。两者之间有很大的不同——而且,除了导致错误(如答案中所述)和混淆(如导致错误)之外,不必要地分配和放弃对象的代价是高昂的......
-
另外,对于像
toString()这样的任务,您应该使用循环而不是递归。因为 Java 没有优化尾递归调用,所以用长列表调用这种实现会导致可怕的堆栈溢出!
标签: java algorithm linked-list singly-linked-list