无法使用链接列表将元素添加到队列的后部

时间:2013-10-17 20:51:08

标签: java linked-list queue

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

}

1 个答案:

答案 0 :(得分:0)

首先,我建议您正确缩进代码并遵循Code Conventions for the Java Programming Language

您的代码中存在一些错误,主要是因为您以错误的方式使用该分配(请参阅下文):

  • 在你写的Node课程中

    public Node(int d){     d =数据; }

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

public Node(int d) {
        data = d;
}
  • queue类,方法enqueue
  • 中的相同内容

newNode = rear;应该是rear = newNode;newNode = front;应为front = newNode;

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

希望这很有用!