# 数据结构与算法~数据结构之队列和环形队列

数组模拟队列编写一个ArrayQueue类实现队列和环形队列


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)]);
}
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

yucan1234

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

©️2020 CSDN 皮肤主题: 黑客帝国 设计师:上身试试