我正在进行一项任务,我需要在给定模板的情况下创建链接列表。但是,到目前为止,我一直难以打印出如何打印链表。任何人都可以弄清楚我做错了什么?
编辑: 对不起,我应该指出,当我编译时,我在NumberList的第27行遇到了java.lang.NullPointerException错误。
编译时出现错误。
NumberList.java
tell application "System Events"
close window "Open Source" of application "VLC"
end tell
tell application "System Events"
click button "Cancel" of window "Open Source" of application "VLC"
end tell
tell application "System Events"
cancel window "Open Source" of application "VLC"
end tell
tell application "System Events" to tell (window 1 of application "VLC" whose subrole is "AXDialog") to close
Node.java
import java.util.*;
public class NumberList {
private Node head;
public NumberList() {
}
public void insertAtHead(int x) {
Node newNode = new Node(x);
if (head == null)
head = newNode;
else {
newNode.setNext(head);
head = newNode;
}
}
public void insertAtTail(int x) {
}
public void insertInOrder(int x) {
}
public String toString() {
Node tmp = head;
String result = "";
while (tmp.getNext() != null) {
result += tmp.toString() + " ";
}
return result;
}
//---------------------
// test methods
//---------------------
public static void testInsertAtHead() {
Random r = new Random();
int n = 20;
int range = 1000;
NumberList list = new NumberList();
for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertAtHead(x);
System.out.println("" + x + ": " + list);
}
}
public static void testInsertAtTail() {
Random r = new Random();
int n = 20;
int range = 1000;
NumberList list = new NumberList();
for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertAtTail(x);
System.out.println("" + x + ": " + list);
}
}
public static void testInsertInOrder() {
Random r = new Random();
int n = 20;
int range = 1000;
NumberList list = new NumberList();
for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertInOrder(x);
System.out.println("" + x + ": " + list);
}
}
public static void main(String[] args) {
//testInsertAtHead();
//testInsertAtTail();
testInsertInOrder();
}
}
答案 0 :(得分:2)
你的问题是:
while (tmp.getNext() != null) {
result += tmp.toString() + " ";
}
您根本没有进入列表中的下一个链接。你应该考虑执行
tmp = tmp.getNext()
。但在此之前,请确保您的while
条件为
while (tmp != null)
以避免NullPointerException
。
你进入第27行的NullPointerException
(我们无法知道它在哪里)可能是因为head
未被初始化,因为你致电{在insertInOrder
之前{1}},这是insertAtHead
在您的计划中初始化的唯一地方。
答案 1 :(得分:0)
您正在调用insertAtTail和insertInOrder方法,但它们是空的。和你的NumberList构造函数一样。