隊列:先進先出;隊頭刪除,隊尾插入
屬性:隊頭指針front,隊尾指針rear
方法:入列enQueue,出列deQueue,判斷是否爲空isEmpty,判斷是否已滿isFull,清空makeEmpty,返回元素個數sizejava
循環隊列java代碼this
public class MyQueue{
private int front = 0,rear = 0;
private String[] queue;指針
public MyQueue(int maxSize){
queue = new String[maxSize];
}隊列
//入列
public void enQueue(String item){
if(rear == queue.length && front > 0)
rear = 0;
if(!this.isFull())
queue[rear++] = item;
}it
//出列
public void deQueue(){
if(front == queue.length && rear > 0)
front = 0;
if(!this.isEmpty())
queue[front++] = null;
}class
//判空
public boolean isEmpty(){
if(front == rear){
return true;
}else{
return false;
}
}test
//判滿
public boolean isFull(){
if(front ==( rear + 1)% (queue.length + 1)){
return true;
}else{
return false;
}
}循環
//返回元素個數
public int size(){
if(rear >= front)
return rear - front;
else
return queue.length + 1 - front + rear;
}queue
//清空
public void makeEmpty(){
rear = front;
}方法
//驗證
public static void main(String[] args){
MyQueue mq = new MyQueue(3);
mq.enQueue("Hello");
mq.enQueue("World");
mq.enQueue("!");
System.out.println("size: "+mq.size());
System.out.println("full? "+mq.isFull());
mq.deQueue();
System.out.println("size: "+mq.size());
System.out.println("full? "+mq.isFull());
mq.enQueue("test");
System.out.println("size: "+mq.size());
System.out.println("full? "+mq.isFull());
mq.makeEmpty();
System.out.println("size: "+mq.size());
System.out.println("full? "+mq.isFull());
System.out.println("empty? "+mq.isEmpty());
}
}