# [Java算法分析与设计]顺序循环队列的实现

package com.chen.arithmetic_test.queue_test;

/**
* Created by ChenMP on 2017/7/5.
*/
public interface Queue {
//入队
public void append(Object obj) throws Exception;
//出队
public Object delete() throws Exception;
//获取头元素
public Object getFront() throws Exception;
//队列是否为空
public boolean isEmpty();

}


package com.chen.arithmetic_test.queue_test;

/**
* Created by ChenMP on 2017/7/5.
* 顺序循环队列实现
*  满足先进先出的实现
*  顺序循环队列跟普通顺序队列的差别在于预防了假溢出的状态
*/
public class CircleSequenceQueue implements Queue {
private Object[] queueData; //队列数组
private int maxSize; //队列最大长度
private int size; //队列大小
private int rearIndex; //队尾位置
private int frontIndex; //对首位置

public CircleSequenceQueue() {
this.maxSize = 10; //设置默认大小
this.size = 0;
this.rearIndex = 0;
this.frontIndex = -1;
this.queueData = new Object[maxSize];
}

public CircleSequenceQueue(int maxSize) {
this.maxSize = maxSize;
this.size = 0;
this.rearIndex = 0;
this.frontIndex = -1;
this.queueData = new Object[maxSize];
}

@Override
public void append(Object obj) throws Exception {
if (size == maxSize)
throw new Exception("队列已满!!!");

this.queueData[rearIndex] = obj;
this.rearIndex = rearIndex+1==this.maxSize?0:++rearIndex; //如果队列数组游标到了数组尾部，转至0位置
this.size++;

}

@Override
public Object delete() throws Exception {
if (0 == size)
throw new Exception("队列为空!!!");

this.frontIndex = frontIndex+1==this.maxSize?0:++frontIndex; //如果队列数组游标到了数组尾部，转至0位置
this.size--;
return this.queueData[frontIndex];
}

@Override
public Object getFront() throws Exception {
if (0 == size)
throw new Exception("队列为空!!!");
int index = frontIndex+1==this.maxSize?0:frontIndex+1;
return this.queueData[index];
}

@Override
public boolean isEmpty() {
return size>0?false:true;
}
}


package com.chen.arithmetic_test.queue_test;

/**
* Created by ChenMP on 2017/7/5.
*/
public class Test {
public  static void main(String[] args) throws Exception {
CircleSequenceQueue queue = new CircleSequenceQueue(12);

for (int i=0; i<12; i++) {
queue.append(i);
}

for (int i=0; i<3; i++) {
System.out.print(queue.delete() + " ,");
}

System.out.println();

queue.append(12);
queue.append(12);
queue.append(12);

while (!queue.isEmpty()) {
System.out.print(queue.delete() + " ,");
}
}
}