我正在尝试通过使用链表实现来执行此队列程序,但它在 pop() 方法上返回 NullPointerException 错误。该程序既不添加元素也不删除队列中的元素。我不知道我做错了什么。请帮我 !!!!!!!!!
public class Node {
public int data;
public Node next;
public Node(int d){
d = data;
}
public void printNode(){
System.out.println(" { " + data + " } ");
}
}
import java.util.*;
public class queue {
public Node front;
public Node rear;
public int size;
public queue(){
front = null;
rear = null;
size = 0;
}
public boolean isEmpty(){
return front == null;
}
public void enqueue(int data){
Node newNode = new Node(data);
if (isEmpty())
newNode = front ;
else
rear.next = newNode;
newNode = rear;
}
public int pop (){
int temp = front.data;
if (front.next == null)
rear =null;
front = front.next;
return temp;
}
public int peek(){
return front.data;
}
public int size(){
Node current = front;
while (current != null){
current = current.next;
size ++;
}
return size;
}
public void printList(){
Node current = front;
while(current != null){
current.printNode();
current = current.next;
}
System.out.println(" ");
}
}
public class test {
public static void main(String[] args) {
queue list = new queue();
System.out.println("add elements to the rear: " );
list.enqueue(5);
list.enqueue(6);
list.printList();
System.out.println("delete elements from the front: ");
list.pop();
list.printList();
System.out.println("the size is : " + list.size());
}
}