對於一個項目,我必須創建一個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在這裏也總是爲空?
如何初始化列表? –
我建議使用紙和鉛筆非常仔細地瀏覽代碼,特別是在創建列表並執行第一次插入的情況下。 –
我只用一個空白的構造函數初始化它,因爲它應該準備好用'new LinkedList();' – Imnotanerd