代码实现:
package csdn.wj.linear;
import csdn.wj.assistant.Node;
import csdn.wj.assistant.Queue;
import csdn.wj.assistant.Queue.QueueEmptyException;
public class Queue02 implements Queue {
private Node front;
private Node rear;
private int size;
public Queue02() {
front = new Node(size);
rear = front;
size = 0;
}
//返回队列的大小
public int getSize() {
return size;
}
//判断队列是否为空
public boolean isEmpty() {
return size==0;
}
//数据元素 e入队
public void enqueue(Object e) {
Node p = new Node((int)e);
rear.next = p;
rear = p;
size++;
}
//队首元素出队
public Object dequeue() throws QueueEmptyException {
if (size<1)
throw new QueueEmptyException("错误:队列为空");
Node p = front.next;
front.next = p.next;
size--;
if (size<1) rear = front; //如果队列为空,rear指向头结点
return p.data;
}
//取队首元素
public Object peek() throws QueueEmptyException {
if (size<1)
throw new QueueEmptyException("错误:队列为空");
return front.next.data;
}
}