package com.lee.queue;
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(3);
queue.addQueue(1);
queue.addQueue(2);
queue.addQueue(3);
queue.showQueue();
System.out.println(queue.getQueue());
queue.showQueue();
System.out.println(queue.headQueue());
System.out.println(queue.getQueue());
System.out.println(queue.getQueue());
System.out.println(queue.headQueue());
}
}
class ArrayQueue{
private int maxSize; //队列最大存储容量
private int front; //指向队列头的前一个位置
private int rear; //指向队列尾的位置
private int[] arr; //存放队列的数组
public ArrayQueue(int maxSize){
this.maxSize = maxSize;
arr = new int[maxSize];
front = -1;
rear = -1;
}
//判断队列是否满
public boolean isFull(){
return rear == maxSize - 1;
}
//判断队列是否为空
public boolean isEmpty(){
return rear == front;
}
//入队
public void addQueue(int n){
if(isFull()){
System.out.println("队列满,不能入队");
return;
}
rear++; //尾部标志后移
arr[rear] = n; //添加数据
}
//出队
public int getQueue(){
if(isEmpty()){
throw new RuntimeException("队列空,不能出队");
}
front++; //头部标志后移
return arr[front]; //返回数据
}
//显示队列数据
public void showQueue(){
if(isEmpty()){
System.out.println("队列空,没有数据");
}
for(int i = 0; i < arr.length; i++){
System.out.println("arr["+ i +"]=" + arr[i]);
}
}
//显示队列头数据
public int headQueue(){
if(isEmpty()){
throw new RuntimeException("队列空,没有数据");
}
return arr[front + 1];
}
}
Java数据结构与算法之队列
猜你喜欢
转载自blog.csdn.net/qq_41286145/article/details/103755922
今日推荐
周排行