【发布时间】:2020-04-02 14:34:19
【问题描述】:
我在我的数据结构课程中有这个实验室植入/编码来使用线性链接列表做一个队列,但它在我的显示方法中抛出了一个NullPointerException,我不知道我的故障点在哪里
Queue链表类代码:
package lab10_moudhi;
/**
*
* @author Moudhi
*/
public class QueueLinkedList<E> {
private static class Node<E>{
private E data;
private Node<E> next;
public Node(E data, Node<E> next) {
this.data = data;
this.next = next;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
@Override
public String toString() {
return data + "";
}
}
private Node<E> front=null,rear=null;
private int size=0;
public QueueLinkedList() {
}
public boolean isEmpty(){
return size==0;
}
public int size(){
return size;
}
public Node<E> getFront(){
if(isEmpty()) return null;
return front;}
public Node<E> getRear(){
if(isEmpty()) return null;
return rear;}
public void enQueue(E value){
System.out.println(value+" - Added to Queue");
Node newNode=new Node(value,null);
if(isEmpty()){
front=rear=newNode;
}
else{
rear.next=newNode;
rear=newNode;
}
size++;
}
public Node<E> deQueue(){
if(isEmpty()){
System.out.println("Queue underflow");
return null;
}
E temp=front.data;
front=front.next;
rear.next=front;
size--;
System.out.println(temp+" -Deleted from Queue");
if(size==0) front=rear=null;
return (Node<E>) temp;
}
public void display(){
Node current=front;
System.out.println("----------------------Display Queue----------------------");
if(isEmpty()){
System.out.println("Empty Queue!!");
return ;
}
do{
System.out.println(current.getData());//it throws the null pointer error here
current=current.next;
}while(current!=front);
System.out.println("--------------------------------------------------------");
}
}
女仆方法::
package lab10_moudhi;
/**
*
* @author Moudhi
*/
public class Lab10_moudhi {
public static void main(String[] args) {
System.out.println("Testing a Queue using Linear Linked List:");
System.out.println("--------------------------------------------");
QueueLinkedList q1= new QueueLinkedList();
q1.enQueue(10);
q1.enQueue(20);
q1.enQueue(30);
q1.enQueue(40);
q1.display();// when i call this method it throws a null pointer exception
q1.deQueue();
q1.deQueue();
System.out.println("Front Element:"+q1.getFront());
System.out.println("Rear Element:"+q1.getRear());
q1.enQueue(50);
q1.display();
}
}
它抛出以下错误::
run:
Testing a Queue using Linear Linked List:
--------------------------------------------
10 - Added to Queue
20 - Added to Queue
30 - Added to Queue
40 - Added to Queue
Exception in thread "main" java.lang.NullPointerException
----------------------Display Queue----------------------
10
20
30
40
at lab10_moudhi.QueueLinkedList.display(QueueLinkedList.java:93)
at lab10_moudhi.Lab10_moudhi.main(Lab10_moudhi.java:16)
C:\Users\Moudhi\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
【问题讨论】:
标签: java data-structures linked-list queue