队列
循环队列
package queue;
public class CircularQueue {
private int first; //队首数据
private int last; //队尾数据
private Object[] array;
//无参构造
public CircularQueue() {
this(6); //调用有参构造
}
//有参构造
public CircularQueue(int length) {
array = new Object[length];
first = -1;
last = -1;
}
//获取队首数据所在队列的位置
public final int getFirst() {
if(isEmpty()) {
throw new RuntimeException("队列为空,无法获取队首数据位置");
}else if(first == -1) { //存在数据时,第一次时获取时,队首的位置由-1改为0
return 0;
}
return first%array.length;
}
//获取队尾数据所在队列的位置
public final int getLast() {
if(isEmpty()) {
throw new RuntimeException("队列为空,无法获取队尾数据位置");
}else if(last == -1) { //存在数据时,第一次时获取时,队尾的位置由-1改为0
return 0;
}
return last%array.length;
}
//判断队列是否为空
public boolean isEmpty() {
if(first !=-1) {
return first-1==last;
}
return first == last;
}
// 添加数据
public void add(Object e) {
if ((last + 1) % array.length == first || last - first == 6) {
throw new RuntimeException("队列已满");
}
// 队尾指针先向后移动,在赋值到队尾
array[(++last) % array.length] = e;
}
// 获取数据
public Object get() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}else if (first == -1) {
first = 0;
return array[(first++) % array.length];
} else {
return array[(first++) % array.length];
}
}
// 打印队列,从队首数据到队尾数据
public String showFirstToLast() {
StringBuffer buffer = new StringBuffer("[");
if (isEmpty()) { // 判断是否为空队列
;
} else if (first == -1) { // 判断是否有出过队列的数据,条件成立则没有出过,且此时first<last
for (int temp = 0; temp <= last; temp++) {
if (temp == last) {
buffer.append(array[temp]);
} else {
buffer.append(array[temp] + ",");
}
}
} else if(first > last) { // 判断是否循环了,条件成立则此时已经循环
for (int temp = first; temp <= last + array.length; temp++) {
if (temp == last) {
buffer.append(array[temp]);
} else {
buffer.append(array[temp] + ",");
}
}
} else {
for (int temp = first; temp <= last; temp++) {
if (temp == last) {
buffer.append(array[temp%array.length]);
} else {
buffer.append(array[temp%array.length] + ",");
}
}
}
buffer.append("]");
return buffer.toString();
}
}
编辑思路
图片在新窗口打开


浙公网安备 33010602011771号