import java.util.NoSuchElementException;
public class ListQueue implements MyQueue {
private class Node {
T item;
Node next;
public Node(T item) {
this.item=item;
}
}
private Node head = null;
private Node tail = null; // root node
private int size = 0;
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void enqueue(T item) {
Node temptail = new Node(item);
if (isEmpty()) {
tail = temptail;
} else {
tail.next = temptail;
}
size++;
}
/**
* dequeue: remove and return the head of the queue
*
* @return the deleted value
* @throws NoSuchElementException if queue is empty
*/
public T dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("the list is empty, cannot be taken data");
}
else if (size()==1) { // when list just only has one elements
head = null;
} else {
head = head.next;
}
size--;
return null;
}
/**
* peek: view the head of queue without removing it.
*
* @return Null if queue is empty
*/
public T peek() {
// if array is empty, cannot view its head
if (isEmpty()) {
return null;
}
return head.item;
}
}
public class Driver{
public static void main(String[] args) {
MyQueue<Integer> q;
boolean useList = true; // make it false if you want to array implementation
if (useList)
q = new ListQueue<Integer>();
else
q = new ArrayQueue<Integer>();
for(int i = 0; i < 1000; i++) // add a large number of items onto the queue
{
q.enqueue(i);
}
System.out.println("now, dequeue items!");
while(!q.isEmpty())
{
System.out.print(q.dequeue() + " ");
}
System.out.println("end of dequeueing");
}
}
//运行程序以后错误是now, dequeue items!
Exception in thread "main" java.lang.NullPointerException
at yao.as1.ListQueue.dequeue(ListQueue.java:73)
at yao.as1.Driver.main(Driver.java:24)
还请给点思路