数组实现循环队列
程序员文章站
2024-03-18 11:17:28
...
/**
* 使用size控制 end 和 start
* @author 小纸人
*
*/
public class MyLoopQueue {
private Integer[] arr;
private Integer start;
private Integer end;
private Integer size;
public MyLoopQueue(int initSize) {
arr = new Integer[initSize];
start = end = size = 0;
}
public void push(int num) {
if(size == arr.length)
throw new RuntimeException("循环队列已满");
size++;
arr[end] = num;
end = end == arr.length - 1 ? 0 : end + 1;
}
public Integer pop() {
if(size == 0)
throw new RuntimeException("循环队列已空");
size--;
int temp = start;
start = start == arr.length - 1 ? 0 : start + 1;
return arr[temp];
}
//获取队头
public Integer peek() {
if(size == 0)
return null;
return arr[start];
}
public static void main(String[] args) {
int[] arr = {3,2,5,8,4,7};
MyLoopQueue loopQueue = new MyLoopQueue(arr.length);
for (int i = 0; i < arr.length; i++) {
loopQueue.push(arr[i]);
}
//
System.out.println("循环队列输出为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(loopQueue.pop()+" ");
}
//System.out.println("peek:"+loopQueue.peek());
}
}
下一篇: Java集合框架-Queue