和栈相反,队列是一种先进后出的数据结构
这里还是采用最简单的数组来实现和前面栈的实现比较类似,只是这里用了两个指针:
下面贴出代码:
package aa;
public class Queue {
private Object[] data=null;
private int maxSize;//队列的大小
private int front;//队头
private int rear;//队尾
public Queue(int maxSize) {
super();
this.maxSize = maxSize;
data=new Object[maxSize];
front=rear=0;
}
//判断队列是否为空
public boolean isEmpty(){
return rear==front?true:false;
}
//插入元素
public boolean add(Object object){
if(rear==maxSize){
throw new RuntimeException("队列已满,无法插入元素!");
}
else{
data[rear++]=object;
return true;
}
}
//出队
public Object poll(){
if(isEmpty()){
throw new RuntimeException("队列为空!");
}
else{
return data[front++];
}
}
//返回队首元素
public Object peek(){
if(isEmpty()){
throw new RuntimeException("队列为空!");
}
else{
return data[front];
}
}
//返回队尾元素
public Object end(){
if(isEmpty()){
throw new RuntimeException("队列为空!");
}
else{
return data[rear-1];
}
}
//获取队列的长度
public int length(){
return rear;
}
public static void main(String[] args){
Queue q=new Queue(10);
q.add(1);
q.add(2);
q.add("pg");
q.add("sf");
q.add("pf");
q.add("sg");
q.add("c");
/*System.out.println(q.length());*/
for(int i=0;i<q.length();i++){
System.out.println(q.poll());
}
}
}