数据结构与算法~数据结构之队列和环形队列
程序员文章站
2022-07-09 18:50:42
...
数组模拟队列编写一个ArrayQueue类实现队列和环形队列
其中环形队列的增加是一个难点,注意新增了一个count计数的变量
public class test {
public static void main(String[] args){
// ArrayQueue arrayQueue=new ArrayQueue(5);
// arrayQueue.addArrayQueue( 1 );
// arrayQueue.addArrayQueue( 2 );
// arrayQueue.addArrayQueue( 3 );
// arrayQueue.showQueue();
// System.out.println( arrayQueue.getQueue() );
// arrayQueue.showQueue();
// arrayQueue.headQueue();
RingQueue ringQueue=new RingQueue(5);
ringQueue.addArrayQueue( 1 );
ringQueue.addArrayQueue( 2 );
ringQueue.addArrayQueue( 3 );
System.out.println( ringQueue.getQueue() );
ringQueue.showQueue();
ringQueue.addArrayQueue( 2 );
ringQueue.addArrayQueue( 3 );
ringQueue.addArrayQueue( 2 );
ringQueue.showQueue();
ringQueue.headQueue();
}
}
class ArrayQueue{
private int maxSize; //最大容量
private int front; //头
private int rear; //尾
private int[] arr; //数组
//创建队列的构造器
public ArrayQueue(int size){
maxSize=size;
front=-1;
rear=-1;
arr=new int[maxSize];
}
public boolean isFull(){
return rear==maxSize-1;
}
public boolean isEmpty(){
return rear==front;
}
public void addArrayQueue(int num){ //入队
if(isFull()){
throw new RuntimeException("队列已满,无法加入数据");
}else{
rear++;
arr[rear]=num;
}
}
public int getQueue(){ //出队
if(isEmpty()){
throw new RuntimeException("队列为空,无法输出数据");
}else{
front++;
return arr[front];
}
}
public void showQueue(){
System.out.print("当前队列内容为:");
for(int i=front+1;i<=rear;i++){
System.out.print(arr[i]+" ");
}
System.out.println( );
}
public void headQueue(){
System.out.println("队列头为:"+arr[front+1]);
}
}
//环形队列
class RingQueue{
private int maxSize; //最大容量
private int front; //头
private int rear; //尾
private int[] arr; //数组
private int count;
//创建队列的构造器
public RingQueue(int size){
maxSize=size;
front=-1;
rear=-1;
count=0;
arr=new int[maxSize];
}
public boolean isFull(){
return rear-front==maxSize;
}
public boolean isEmpty(){
return rear==front;
}
public void addArrayQueue(int num){ //入队
if(isFull()){
throw new RuntimeException("队列已满,无法加入数据");
}else{
rear++;
arr[(rear-front+count-1)%maxSize]=num;
}
}
public int getQueue(){ //出队
if(isEmpty()){
throw new RuntimeException("队列为空,无法输出数据");
}else{
front++;
count++;
return arr[front%maxSize];
}
}
public void showQueue(){
if(isEmpty()){
throw new RuntimeException("队列为空,无法输出数据");
}else {
System.out.print("当前队列内容为:");
for(int i=front+1;i<=rear;i++){
System.out.print(arr[i%maxSize]+" ");
}
System.out.println( );
}
}
public void headQueue(){
if(isEmpty()){
throw new RuntimeException( "队列为空" );
}
System.out.println("队列头为:"+arr[(front%maxSize)]);
}
}