public class queue{
private object[] data=null;
private int maxsize; //队列容量
private int front; //队列头,允许删除
private int rear; //队列尾,允许插入
//构造函数
public queue(){
this(10);
}
public queue(int initialsize){
if(initialsize >=0){
this.maxsize = initialsize;
data = new object[initialsize];
front = rear =0;
}else{
throw new runtimeexception("初始化大小不能小于0:" + initialsize);
}
}
//判空
public boolean empty(){
return rear==front?true:false;
}
//插入
public boolean add(e e){
if(rear== maxsize){
throw new runtimeexception("队列已满,无法插入新的元素!");
}else{
data[rear++]=e;
return true;
}
}
//返回队首元素,但不删除
public e peek(){
if(empty()){
throw new runtimeexception("空队列异常!");
}else{
return (e) data[front];
}
}
//出队
public e poll(){
if(empty()){
throw new runtimeexception("空队列异常!");
}else{
e value = (e) data[front]; //保留队列的front端的元素的值
data[front++] = null; //释放队列的front端的元素
return value;
}
}
//队列长度
public int length(){
return rear-front;
}
}