2014-04-01 40 views
0

對於一個項目,我必須創建一個LinkedList類,它將連接僅包含Temperature對象的ListNode對象和對下一個ListNode的引用連接起來。這些類運行良好,但在LinkedList類中,我無法弄清楚爲什麼當我嘗試將它分配給某些內容時,「n」總是爲空。爲什麼在列表中插入一個元素時n總是爲空?

的LinkedList:

public class LinkedList { 
ListNode ln = new ListNode(); 
private ListNode first = ln; 
private ListNode last = ln; 
private int length = 0; 

public void append(Temperature s) { 
    ListNode n = new ListNode(s); 
    last.next = n; 
    last = n; 
    length++; 
} 

public void printList(TemperatureGUI gui) { 
    ListNode p = first.next; 
    while (p != null) { 
     //gui.listAppend(Float.toString(p.data.getTemperature()) + "\n"); 
     System.out.println(p.data.getTemperature()); 
     p = p.next; 
    } 
} 

public ListNode find(Temperature s) { 
    ListNode n = first.next; 
    while (n != null && !(n.data).equals(s)) { 
     n = n.next; 
    } 
    return n; 
} 

public void insert(Temperature temp) { 
    ListNode n = first.next; 
    ListNode x = new ListNode(temp); 

    // if it's the first element in the linked list, 
    // make the parameter the first in the list 
    if (n == null) { 
     n = x; 
     length++; 
     System.out.println(length); 
     return; 
    } 

    while (n != null && 
      n.next != null && 
      n.data.compareTo(temp) == -1) { // -1 means data is less than temp 
     if (n.next.data.compareTo(temp) == 1) { // 1 means data is greater than temp 
      break; 
     } 
     n = n.next; 
    } 

    // if it's the last element on the list, append it to the end 
    if (n.equals(last) && n.next == null) { 
     n.next = x; 
     last = x; 
     length++; 
     return; 
    } 

    x.next = n.next; 
    n.next = x; 
    length++; 
} 

}

的問題就在這裏:

if (n == null) { 
     n = x; 
     length++; 
     System.out.println(length); 
     return; 
    } 

它始終打印長度,沒有別的運行。爲什麼即使賦值給它,n在這裏也總是爲空?

+0

如何初始化列表? –

+1

我建議使用紙和鉛筆非常仔細地瀏覽代碼,特別是在創建列表並執行第一次插入的情況下。 –

+0

我只用一個空白的構造函數初始化它,因爲它應該準備好用'new LinkedList();' – Imnotanerd

回答

3
ListNode n = first.next; //n is a reference to first.next 
n = x; // n is no longer a reference to first.next 

n是該方法的局部變量。所以無論你對n做什麼,它都不會影響到第一個和最後一個全局引用。

因此,每次調用方法時,n都爲null,因爲first.next始終爲空。所以做任務作爲

first.next = x; // instead of n = x; 
+0

'first'和'last'分享一個參考,這也是一個問題。 –

+0

ohhh OP期待** n **成爲** first.next的參考**我現在明白了。 – Scott

+0

在此期間,我忘記了所有關於範圍的事情,但現在它運行得更有預期。謝謝! – Imnotanerd

1

當你說

ListNode n = first.next; 

您聲明一個新的變量,並以相同的對象first.next參考實例吧。此代碼如下:

if (n == null) { 
    n = x; 
    length++; 
    System.out.println(length); 
} 

將更改變量n中包含的引用,但請注意first.next未被修改。這是因爲行

ListNode n = first.next; 

不提供對變量first.next的引用,而是將first.next的值複製到n中。

編輯:要真正解決這個問題,您需要更改

n = x; 

first.next = x; 

雖然它不是你的代碼必不可少的,我也建議使用first.next代替整個代碼中的n個。 'n'不是一個非常具有描述性的變量名,而first.next更具可讀性。它會幫助你的老師和你的同學理解你的代碼,並且不會讓你的程序效率下降。

相關問題