这是一个带有sortedAdded和sortedRemove方法的双链表。当我运行代码时,它将引发“空点异常”。我知道例外在“ 43”行,但我不知道如何解决。我曾在该网站上发表过一篇文章,介绍了如何“防止空值异常”,但仍然做得不好。这是我的代码:
public class DoublyLinkedList<Item extends Comparable> {
private class Node{
private Item item;
private Node next;
private Node prev;
public Node getNext() {
return next;
}
public Node getPrev(){
return prev;
}
public Item getItem(){
return item;
}
public void setNext(Node next) {
this.next = next;
}
public void setPrev(Node prev){
this.prev= prev;
}
public void setItem(Item item){
this.item = item;
}
}
private Node head;
private int numberOfEelements;
public void sortedAdd(Item newItem) {
Node dummy = head;
Node current = dummy.getNext();
while ((newItem.compareTo(current.getItem()) > 0) && (current != dummy))
current = current.getNext();
Node temp = new Node();
temp.setNext(current);
temp.setPrev(current.getPrev());
(current.getPrev()).setNext(temp);
current.setPrev(temp);
temp.setItem(newItem);
++numberOfEelements;
}
public void sortedRemove(Item newItem) {
Node dummy = head;
Node current = dummy.getNext();
while((newItem.compareTo(current.getItem()) !=0) && (current!= dummy))
current = current.getNext();
if (newItem.equals(current.getItem())) {
(current.getPrev()).setNext(current.getNext());
(current.getNext()).setPrev(current.getPrev());
--numberOfEelements;
}
}
public static void main(String[] args) {
DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>();
list.sortedAdd(1);
list.sortedAdd(5);
list.sortedAdd(7);
list.sortedAdd(9);
list.sortedAdd(3);
list.sortedAdd(2);
System.out.println(list);
list.sortedRemove(3);
list.sortedRemove(7);
System.out.println(list);
list.sortedRemove(4);
}
}
这是我得到的错误:
Exception in thread "main" java.lang.NullPointerException
at DoublyLinkedList.sortedAdd(DoublyLinkedList.java:43)
at DoublyLinkedList.main(DoublyLinkedList.java:74)
最佳答案
在sortedAdd中,您不处理head == null(在这种情况下意味着空列表)的初始情况。因此,在dummy.getNext();
行中,您在一个空引用上调用getNext。
为创建一个空头添加一个检查将使您克服此错误:
public void sortedAdd(Item newItem) {
if (head == null) {
head = new Node();
head.setItem(newItem);
++numberOfEelements;
return;
}
尽管由于循环逻辑的原因,您将遇到另一个NPE。
为了打印列表,您将需要添加toString()方法:
public String toString(){
Node current = head;
StringBuilder sb = new StringBuilder();
while(current != null){
sb.append(current).append(" ");
current = current.getNext();
}
return sb.toString();
}