0

我正在尝试通过使用链表实现来执行此队列程序,但它在 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());
}

}

4

1 回答 1

0

首先,我建议您正确缩进您的代码并遵循Java 编程语言的代码约定

您的代码中有一些错误,主要是因为您以错误的方式使用分配(见下文):

  • 在你的Node课上你写了这个

    公共节点(int d){ d =数据;}

但实际上你想要的是这个(必须分配实例变量而不是参数):

public Node(int d) {
        data = d;
}
  • 在您的queue课程中也是如此,方法enqueue

newNode = rear;应该是rear = newNode;而且 newNode = front;应该是front = newNode;

我实际上没有检查功能错误,但至少测试用例似乎工作正常。

希望这很有用!

于 2013-10-18T10:03:36.880 回答