我想插入一个新的节点在列表的末尾,但它不断递归。如何在我的自定义LinkedList实现中避免不必要的递归?
我在做什么错?
public class Main {
public static void main(String[] args) {
run();
}
private static void run() {
LinkedList list = new LinkedList();
list.add("abc");
list.add("def");
list.add("ghi");
list.add("jkl");
}
}
add方法首先检查列表是否为空。
如果是这样,它会创建一个头节点。
否则,它会尝试查找列表的末尾并在其中插入新节点。
public class LinkedList<T> {
Element head;
Element terminator = new Element("TERMINATOR", true);
public void add(T e) {
Element node = new Element(e);
if(head==null){
head = node;
head.setNext(terminator);
}
else {
Element end = getEnd2();
end.setNext(node);
}
}
public Element getEnd2() {
Element tmp;
while((tmp = head.getNext())!=null){
System.out.println("tmp:" + tmp.getValue());
}
return tmp;
}
public Element getEnd(){
Element node = head;
while(node!=null){
System.out.println("node:" + node.getValue());
node = head.getNext();
}
return node;
}
public Element getHead(){
return head;
}
}
public class Element<T>{
T value;
Element<T> next;
boolean terminator;
Element(T value){
this.value = value;
}
Element(T value, boolean terminator){
this.value = value;
this.terminator = terminator;
}
public void setNext(Element<T> next) {
this.next = next;
}
public Element getNext(){
return next;
}
public T getValue(){
return value;
}
public boolean isTerminator() {
return terminator;
}
public void setTerminator(boolean terminator) {
this.terminator = terminator;
}
}
你是什么意思继续递归?代码的结果是什么?期望的结果是什么? – 2014-10-16 15:43:33