循环队列相关背景###
什么是队列就不解释了
头尾相接的顺序存储结构称为循环队列(circular queue)。
循环队列中需要注意的几个重要问题:
①队空的判定条件,队空的条件是front=rear;
②队满的判定条件,(rear+1)%QueueSize=front。QueueSize为队列初始空间大小。
import com.sun.corba.se.impl.orbutil.graph.Node;
import com.sun.corba.se.spi.presentation.rmi.IDLNameTranslator;
/**
* Created by junyi.pc on 2017/1/25.
*/
public class Main {
public int array[];
public int size;
public int front;
public int rear;
public Main(int size){
array =new int[size];
this.size=size;
front=0;
rear=0;
}
public void enqueue(int value){
if((rear+1)%size==front){
//队列满了
throw new ArrayIndexOutOfBoundsException();
}
else{
array[rear]=value;
rear=(rear+1)%size;
}
}
public int dequeue(){
if(rear==front) {
//说明满了
return 0;
}
else{
int temp=front;
front=(front+1)%size;
return array[temp];
}
}
public boolean isEmpty() {
return size == 0;
}
public int getLength(){
if(rear>front){
return rear-front;
}
else {
return array.length-1;
}
}
public static void main(String[] args){
Main queue=new Main(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
}
}
运行结果
C:\java\jdk1.8.0_25\bin\java -Didea.launcher.port=7534 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\java\jdk1.8.0_25\jre\lib\charsets.jar;C:\java\jdk1.8.0_25\jre\lib\deploy.jar;C:\java\jdk1.8.0_25\jre\lib\ext\access-bridge-64.jar;C:\java\jdk1.8.0_25\jre\lib\ext\cldrdata.jar;C:\java\jdk1.8.0_25\jre\lib\ext\dnsns.jar;C:\java\jdk1.8.0_25\jre\lib\ext\jaccess.jar;C:\java\jdk1.8.0_25\jre\lib\ext\jfxrt.jar;C:\java\jdk1.8.0_25\jre\lib\ext\localedata.jar;C:\java\jdk1.8.0_25\jre\lib\ext\nashorn.jar;C:\java\jdk1.8.0_25\jre\lib\ext\sunec.jar;C:\java\jdk1.8.0_25\jre\lib\ext\sunjce_provider.jar;C:\java\jdk1.8.0_25\jre\lib\ext\sunmscapi.jar;C:\java\jdk1.8.0_25\jre\lib\ext\sunpkcs11.jar;C:\java\jdk1.8.0_25\jre\lib\ext\zipfs.jar;C:\java\jdk1.8.0_25\jre\lib\javaws.jar;C:\java\jdk1.8.0_25\jre\lib\jce.jar;C:\java\jdk1.8.0_25\jre\lib\jfr.jar;C:\java\jdk1.8.0_25\jre\lib\jfxswt.jar;C:\java\jdk1.8.0_25\jre\lib\jsse.jar;C:\java\jdk1.8.0_25\jre\lib\management-agent.jar;C:\java\jdk1.8.0_25\jre\lib\plugin.jar;C:\java\jdk1.8.0_25\jre\lib\resources.jar;C:\java\jdk1.8.0_25\jre\lib\rt.jar;C:\Users\junyi.pc\Desktop\client\out\production\client;C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain Main
1
2
3
Process finished with exit code 0