队列:
先进先出(FIFO)。数组实现。
JAVA源码:
import java.util.ArrayList;
class MyQueue<T>{
private int front;
private int rear;
private int size;
private T[] arr;
public MyQueue(){
front=0;
rear=0;
size=0;
arr=(T[])new Object[8];
}
public int size(){
return size;
}
public boolean isEmpty(){
return size==0;
}
public boolean isFull(){
return size==arr.length;
}
public void resize(){
T[] tmp=(T[])new Object[arr.length*2];
System.arraycopy(arr,0,tmp,0,arr.length);
arr=tmp;
tmp=null;
}
public void enQueue(T t){
if(isFull()){
resize();
front=0;
}
rear=(front+size)%arr.length;
arr[rear]=t;
size++;
}
public T deQueue(){
if(isEmpty()){
throw new RuntimeException("Nothing left");
}
T tmp=arr[front];
arr[front]=null;
front=(front+1)%arr.length;
size--;
return tmp;
}
public T front(){
return arr[front];
}
}
public class Queue {
public static void main(String[] args){
MyQueue<Integer> qq=new MyQueue<Integer>();
for(int i=10;i<20;i++){
qq.enQueue(i);
}
System.out.println("SIZE: "+qq.size());
System.out.println("FRONT: "+qq.front());
System.out.println("OUT:"+qq.deQueue());
System.out.println("SIZE: "+qq.size());
System.out.println("FRONT: "+qq.front());
System.out.println("OUT:"+qq.deQueue());
}
}
输出结果: