package com.lee.queue;
public class Queue {
private int maxSize;//隊列長度
private int front; //指向隊列第一個元素的位置,默認值爲0
private int rear; //指向隊列最後一個元素的後一個位置,默認值是0
private int[] data; //存儲隊列的數組
//初始化隊列
public Queue(int maxSize) {
this.maxSize = maxSize;
data = new int[maxSize];
front = 0;
rear = 0;
}
//判斷隊列是否爲空
public boolean isNull() {
return front == rear;
}
//判斷隊列是否爲滿
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
//入隊
public void addQueue(int element) {
//判斷隊列是否爲滿
if(isFull()) {
System.out.println("隊列滿,不能加入");
return;
}
data[rear] = element;
//將rear後移,考慮取模
rear = (rear + 1) % maxSize;
}
//出隊
public int getQueue() {
//判斷是否爲空
if(isNull()) {
throw new RuntimeException("隊列爲空,不能取數據");
}
int value = data[front];
//front後移,考慮取模
front = (front + 1) % maxSize;
return value;
}
//顯示隊列所有數據
public void show() {
if(isNull()) {
System.out.println("隊列空,沒有數據");
return;
}
for(int i = front; i < front + size(); i++) {
System.out.println("data[" + i % maxSize + "]:" + data[i % maxSize]);
}
}
//返回有多少個有效元素
public int size() {
return (rear + maxSize - front) % maxSize;
}
//顯示隊列頭數據
public int peek() {
if(isNull()) {
throw new RuntimeException("隊列爲空");
}
return data[front];
}
}