2010-01-20 70 views
1

所以我正在學習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(); 
    } 
} 
+2

您所顯示的代碼由於構造函數中的this(i,null);而無法編譯。 – 2010-01-20 15:08:15

+0

實際上,您並不是將元素/節點添加到「列表」中,而是每次只覆蓋前一個。 – Kevin 2010-01-20 15:08:25

回答

3

在此塊:

public void push(int i) 
{ 
    stuff = i; 
    next = this; 
} 

要分配節點的next到自身。

試試這個:

public void push(int i) 
{ 
    next = new Cons(i); 
} 

,將刪除自循環,但你仍然有記憶,其中尾巴的問題。因爲這是作業,所以我會把它作爲練習。

在評論中指出的另一個問題是,你的代碼不應該按原樣編譯,因爲你試圖調用一個不存在的構造函數。

如果你想打電話給this(i, null)你需要一個構造函數,它需要(int, Cons)作爲它的arugments。

0

嘗試創建如圖所示的代碼in wikipedia。您需要集裝箱持有節點,節點代表單個節點列表

0

我覺得

next = this 

是不對的,你應該建立新的條目

next = new Cons(stuff); 
stuff = i; 

否則下一個條目指向當前的一個! 請注意,如果你這樣做的元素的順序顛倒..

+0

這也將把價值觀放在錯誤的地方。 – danben 2010-01-20 15:14:44

0
public void push(int i) 
{ 
    stuff = i; 
    next = this; //here's the problem. 
} 

你需要的東西,如:

public void push(int i) 
{ 
    Cons newnext = new Cons(i) 
    tail.next = newnext; 
    tail = newnext; 
} 

,當然你需要你的鏈接尾部的參考列表某處