【发布时间】:2018-03-23 23:45:47
【问题描述】:
我正在创建一个排序链接列表,其中整数按升序存储。我在使用 add() 方法时遇到问题。当我添加第一个节点时它可以工作,但是当我尝试添加另一个节点时它给了我NullPointerException
这是我的 Node 类代码:
public class Node {
int value;
Node next;
public Node() {
}
public Node(int c) {
this.value = c;
}
public boolean hasNext() {
if (next == null) {
return false;
} else {
return true;
}
}
这是我的 SortedList 类的一部分:
public class SortedList {
Node head;
public int listCount;
public SortedList() {
listCount = 0;
this.head=null;
}
public void add(int num) {
Node newNode = new Node(num);
Node temp = head;
if (head == null) {
head = newNode;
listCount++;
System.out.println("Node with data "+num+" was added.");
} else {
while (temp.value <= num) { //the compiler shows NullPointerException here in this line
temp = temp.next;
}
if (temp.next==null) {
temp.next=newNode;
listCount++;
System.out.println("Node with data "+num+" was added.");
} else {
newNode.next=temp.next.next;
temp.next=newNode;
listCount++;
System.out.println("Node with data "+num+" was added.");
}
}
}
它说 java.lang.NullPointerException 在“while (temp.value
【问题讨论】:
-
所以想想如果你添加的数字大于列表中已经存在的每个数字会发生什么。在我看来,这个循环会一直持续到
temp变为空,这不可能是你想要的,对吧?
标签: java linked-list singly-linked-list