-1

我一直在尝试编写一个使用 Node 文件的队列,但我似乎无法弄清楚空指针异常的问题所在。我在网上看了一点,但我对 Java 太陌生了,我想我无法理解我在这里寻找什么。任何人都可以找到它或至少将我引向正确的方向吗?

首先是队列:

public class Queue extends CharNode {
public CharNode head;
public CharNode tail;

public Queue(){
    this.head = null;
    this.tail = null;}

public boolean isEmpty(){
    return (head==null);}

public void enqueue(Character character){
    if (isEmpty()){
        head.character = character;
        head.nextNode = tail;}
    else {
        CharNode oldTail = tail;
        tail = new CharNode();
        oldTail.character = character;
        oldTail.nextNode = tail;
    }
    }

public Character dequeue(){
    if (isEmpty()) throw new RuntimeException("Queue Empty");
    head.character = character;
    head = head.nextNode;
    return character;
}       
public static void main(String[] args){
    Queue queue = new Queue();
    queue.enqueue('a');
    queue.enqueue('b');
    System.out.print(queue.dequeue());
}

}

我的 CharNode 文件如下所示:

public class CharNode {
public Character character;
public CharNode nextNode;
public void charNode(Character character){
    this.character = character;
    this.nextNode = null;
}

}

我收到的异常如下所示:

Exception in thread "main" java.lang.NullPointerException
at Queue.enqueue(Queue.java:14)
at Queue.main(Queue.java:32)
4

2 回答 2

5
public boolean isEmpty(){
    return (head==null);}

public void enqueue(Character character){
    if (isEmpty()){
        head.character = character;   // you have just said that head is NULL

可能有效的是

if (isEmpty()){
        head = new CharNode ();     // There is no Constructor for CharNode (Character)
        head.character = character;
于 2013-10-21T05:30:14.157 回答
0

如果 head 为空,isEmpty() 返回 true。并且您尝试在导致 NPE 的 enqueue method() 中使用空对象的值。这一行:head.character = character;

于 2013-10-21T05:34:47.193 回答