我正在尝试使用链表实现来执行此队列程序,但它在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());
}
}
首先,我建议您正确缩进代码并遵循 Java 编程语言的代码约定。
代码中有一些错误,主要是因为您以错误的方式使用赋值(见下文):
-
在你的
Node
课上你写了这个public Node(int d) { d = 数据;}
但实际上你想要的是这个(必须分配实例变量而不是参数):
public Node(int d) {
data = d;
}
- 在您的
queue
类中也是如此,方法enqueue
:
newNode = rear;
应该rear = newNode;
和 newNode = front;
应该front = newNode;
我实际上没有检查功能错误,但至少在测试用例中,似乎可以正常工作。
希望这有用!