【发布时间】:2014-04-01 03:01:11
【问题描述】:
对于一个项目,我必须创建一个 LinkedList 类来连接仅包含温度对象的 ListNode 对象,以及对下一个 ListNode 的引用。这些类运行良好,但在 LinkedList 类中,当我尝试将“n”分配给某个东西时,我无法弄清楚为什么它总是为空。
链表:
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(); -
ListNode长什么样子?
标签: java linked-list