【发布时间】:2014-08-21 14:29:27
【问题描述】:
我正在编写一个简单的链表实现和相应的触发器类,如下所示:
public class Trigger {
public static void main(String[] args) {
LinkedList lin = new LinkedList();
lin.add(3);
lin.add(4);
lin.add(5);
lin.display();
}
}
public class LinkedList {
Item startItem;
LinkedList() {
startItem = new Item();
}
public void add(Integer newValue) {
if(startItem.value == null) {
startItem.value = newValue;
return;
}
Item tempItem = new Item();
tempItem.value = newValue;
while(startItem.next != null) {
startItem = startItem.next;
}
startItem.next = tempItem;
}
public void display() {
while(true) {
System.out.println("\t"+ startItem.value);
if(startItem.next == null) {
break;
} else {
startItem = startItem.next;
}
}
}
class Item {
Integer value;
Item next;
Item() {
this.value = null;
this.next = null;
}
}
}
问题是,只有最后两个添加被保留,而之前的添加被丢弃。这是(当然)因为我不断更改引用 startItem 指向的对象。我的问题是,给定这样的递归结构,正确的循环机制是什么?我知道在链表中,不需要到达链表的末尾来执行加法。链表结构用作询问循环遍历递归结构的上下文。谢谢。
【问题讨论】:
-
您可以随时查看
java.util.LinkedList的源代码,看看它是如何实现的。
标签: java loops recursion linked-list