队列
数组简易队列
public class ArrayQueue{
private int maxSize;
private int front;
private int rear;
private int[] arr;
public ArrayQueue(int arrMaxSize){
this.maxSize = arrMaxSize;
this.arr = new int[this.maxSize];
front = -1;
rear = -1;
}
public boolean isFull(){
return rear == maxSize -1;
}
public boolean isEmpty(){
return rear == front;
}
pulic 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("队列空的");
return;
}
for(int i=0;i<arr.length;i++){
System.out.printf("arr[%d]=%d",i,arr[i]);
}
}
public int headQueue(){
if(isEmpty()){
throw new RuntimeException("队列空");
}
return arr[front+1];
}
}
数组环形队列
- front
- rear
- 队列满条件
- 队列空条件
- 队列有效值个数
- (rear+maxSize-front)%maxSize
public class CircleArray{
private int maxSize;
private int front;
private int rear;
private int[] arr;
public CircleArray(int arrMaxSize){
this.maxSize = arrMaxSize;
this.arr = new int[this.maxSize];
this.front = 0;
this.rear = 0;
}
public boolean isFull(){
return (rear+1)%maxSize == front;
}
public boolean isEmpty(){
return rear == front;
}
pulic void addQueue(int n){
if(isFull()){
System.out.println("队列满,不能加入");
return;
}
arr[rear] = n;
rear = (rear+1)%maxSize;
}
public int getQueue() {
if(isEmpty()){
throw new RuntimeException("队列空,不能取");
}
int temp = arr[front];
front = (front+1)%maxSize;
return temp;
}
public void showQueue(){
if(isEmpty()){
System.out.println("队列空的");
return;
}
for(int i=front;i<front+size();i++){
System.out.printf("arr[%d]=%d",i%maxSize,arr[i%maxSize]);
}
}
public int size(){
return (rear+maxSize-front)%maxSize;
}
public int headQueue(){
if(isEmpty()){
throw new RuntimeException("队列空");
}
return arr[front];
}
}