java实现环形队列
程序员文章站
2024-03-18 11:26:40
...
/**
* 队列:先进先出
* 数组实现
* first in first out
* FIFO
*/
public class MyQueue {
private Object[] arr = new Object[5];
private int start = 0;
private int end = 0;
//插入元素
public boolean offer(Object obj){
if((end+1)%arr.length == start){
return false;
}
arr[end] = obj;
end++;
end = end%arr.length;
return true;
}
//查看队头元素
public Object peek(){
return arr[start];
}
//弹出元素
public Object poll(){
if(start == end){
throw new NullPointerException();
}
Object temp = arr[start];
start++;
start = start%arr.length;
return temp;
}
//获取队列内容长度
public int size(){
return (end+arr.length-start)%arr.length;
}
}