使用数组实现环形队列
package com.codezs.datastruct.queue;
public class CircleQueue {
private String[] items;
private int size = 0;
//指向队列头部
private int head = 0;
//指向队列尾部
private int tail = 0;
public CircleQueue(int capacity) {
items = new String[capacity];
this.size = capacity;
}
//入队
public boolean enqueue(String item) {
//队列已满
if ((tail + 1) % size == head) return false;
items[tail] = item;
tail = (tail + 1) % size;
return true;
}
//出队
public String dequeue() {
//队列为空时
if (head == tail) return null;
String temp = items[head];
head = (head + 1) % size;
return temp;
}
}