我想插入一個新的節點在列表的末尾,但它不斷遞歸。如何在我的自定義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