我一直在尝试编写一个使用 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)