所以我正在學習Java,我想實現一個單鏈表,但是當我嘗試打印它時,它會進入無限循環,只打印第一個元素,就好像temp
不會被重新分配。這裏有什麼問題?Java:實現列表
public class Cons
{
public int stuff;
public Cons next;
public Cons(int i)
{
this(i, null);
}
public void show()
{
Cons temp = this;
while(temp != null)
{
System.out.println(temp.stuff);
temp = temp.next;
}
}
public void push(int i)
{
stuff = i;
next = this;
}
public static void main(String[] args)
{
Cons head = new Cons(2);
head.push(3);
head.push(12);
head.show();
}
}
您所顯示的代碼由於構造函數中的this(i,null);而無法編譯。 – 2010-01-20 15:08:15
實際上,您並不是將元素/節點添加到「列表」中,而是每次只覆蓋前一個。 – Kevin 2010-01-20 15:08:25