我正在为我为作业设计的课程寻求帮助。它将游戏分数添加到链接列表中,并从最高到最低列出它们。分数的最大数量是 10。我几乎可以工作,但我无法弄清楚。我添加第一个分数并且它有效,然后如果我添加第二个分数,它仅在该分数高于第一个时才有效。如果没有,它会抛出一个java.lang.NullPointerException
. 有人可以看看我的insert(String name, int score)
方法并让我知道问题所在吗?
public class GamerList {
/**
* The node class stores a list element and a reference to the next node.
* @author johnmckillip
*
*/
private class Node {
String name;
int score;
Node next;
/**
* Constructor.
* @param val The element to store in the node.
* @param n The reference to the successor node.
*/
Node(String val1, int val2, Node n) {
name = val1;
score = val2;
next = n;
}
/**
* Constructor.
* @param val The element to store in the node.
*/
Node(String val1, int val2) {
this(val1, val2, null);
}
}
private Node head;
private Node tail;
/**
* Constructor.
*/
public GamerList() {
head = null;
tail = null;
}
/**
* The isEmpty method checks to see if the list is empty.
* @return true if the list is empty, false otherwise.
*/
public boolean isEmpty() {
return head == null;
}
/**
* The size method returns the length of the list.
* @return The number of elements in the list.
*/
public int size() {
int count = 0;
Node p = head;
while(p != null) {
count++;
p = p.next;
}
return count;
}
public void insert(String name, int score) {
Node node = new Node(name, score);
if(isEmpty()) {
head = node;
tail = node;
}
else if(head.score <= node.score) {
node.next = head;
head = node;
}
else {
Node frontPtr = head.next;
Node backPtr = head;
while(frontPtr.score > node.score && frontPtr.next != null) {
backPtr = backPtr.next;
frontPtr = frontPtr.next;
}
if(frontPtr != null && frontPtr.score <= node.score) {
backPtr.next = node;
node.next = frontPtr;
}
else {
frontPtr.next = node;
tail = node;
}
}
if(size() > 10) {
Node currentPtr = head;
while(currentPtr.next != tail) {
currentPtr = currentPtr.next;
}
tail = currentPtr;
currentPtr.next = null;
}
}
public void printList() {
Node temp = head;
while(temp != null) {
System.out.print(temp.name + " " + temp.score + " ");
System.out.println("");
temp = temp.next;
}
}
}
这是我要测试的课程GamerList
:
公共类 TestGamerList {
/**
* @param args
*/
public static void main(String[] args) {
GamerList list1 = new GamerList();
list1.insert("Fry", 89);
list1.insert("Bender", 25);
list1.insert("Leela", 90);
list1.insert("Zoidburg", 23);
list1.insert("Amy", 34);
list1.insert("Hermes", 96);
list1.insert("Zapp",123);
list1.insert("Nibbler", 56);
list1.insert("Calculon", 12);
list1.insert("Hypnotoad", 189);
list1.insert("Lrrr", 5);
list1.insert("Scruffy", 28);
System.out.println("Top 10 Scores: ");
list1.printList();
}
}