/**
*
* 循环队列 FIFO first in first out
* @author liuhaibing
*
*/
public class Queue {
//
private int head;
private int end;
private int size;
private int[] queue;
/**
* 初始化一个size大小的空队列
* @param size
*/
public Queue(int size) {
this.size = size;
queue = new int[size + 1]; // 必须定义size + 1个空间
head = end = 0; // head == end 队列为空
}
public boolean isEmpty() {
if(head == end) {
return true;
}
return false;
}
public boolean isFull() {
int next = 0; // 如果end= size-1
// 特殊情况,end在数组的最后一个元素
if(end == size) {
next = 0;
}else {
next = end + 1;
}
if(next == head) { // 如果尾的下一个是head,说明队列满了
return true;
}else {
return false;
}
}
public void offer(int data) {
int next = 0;
if(!isFull()) {
if(end == size) {
next = 0;
}else {
next = end + 1;
}
queue[end] = data;
end = next;
}else {
throw new IllegalStateException("队列已满");
}
}
public int poll() {
if(!isEmpty()) {
// 取数据
int data = queue[head];
if(head == size) {
head = 0;
}else {
head ++;
}
return data;
}else {
throw new IllegalStateException("队列是空!"); // Alt + /
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue queue = new Queue(5);
queue.offer(1); // 入队
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.offer(5);
// queue.offer(6);
// System.out.println(queue.poll()); // poll出队
// queue.offer(10);
// // queue.offer(11);
// System.out.println(queue.poll()); // 2
// queue.offer(11);
// System.out.println(queue.poll()); // 3
// queue.offer(12);
// System.out.println(queue.poll()); // 4
// queue.offer(13);
// System.out.println(queue.poll()); // 5
// queue.offer(14);
// System.out.println(queue.poll()); // 10
// System.out.println(queue.poll()); // 11
// System.out.println(queue.poll()); // 12
// System.out.println(queue.poll()); // 13
// System.out.println(queue.poll()); // 14
//
// queue.offer(15);
// System.out.println(queue.poll()); // 14
//
// queue.offer(16);
// System.out.println(queue.poll()); // 14
//
// queue.offer(17);
// System.out.println(queue.poll()); // 14
//
// queue.offer(18);
// System.out.println(queue.poll()); // 14
//
//
// queue.offer(19);
// System.out.println(queue.poll()); // 14
//
// queue.offer(20);
// System.out.println(queue.poll()); // 14
//
//
// queue.offer(21);
// System.out.println(queue.poll()); // 14
//
// System.out.println(queue.poll());
}
}