java循环队列代码
时间: 2023-12-24 07:24:07 浏览: 77
Java循环队列代码如下所示:
```
class MyCircularQueue {
private int[] elem;
private int front;
private int rear;
private int size;
public MyCircularQueue(int n) {
elem = new int[n+1];
front = rear = 0;
size = n + 1;
}
public boolean isEmpty() {
return front == rear;
}
public boolean isFull() {
return ((rear+1)%size == front);
}
public boolean enQueue(int value) {
//判断队列是否满
if(isFull()){
return false;
}else {
elem[rear] = value;
rear = (rear+1)%size;
return true;
}
}
public boolean deQueue() {
//队列是否为空
if(isEmpty()){
return false;
}else {
front = (front + 1) % size;
return true;
}
}
public int getFront() {
if(isEmpty()){
throw new RuntimeException("队列为空,无元素!");
}else {
int val = elem[front];
front = (front + 1) % size;
return val;
}
}
public int size(){
return (rear + size - front) % size;
}
}
```
这是一个基于数组实现的循环队列,其中包括了判断队列是否为空、是否已满、入队、出队、获取队头元素等方法。在实现过程中,需要注意队列长度、队列是否满、是否为空时,求算方法不同。
阅读全文