【编程题】用数组实现队列(Java实现)
题目要求
通过一个数组实现队列的功能,具有出队列、压队列、以及当前队列顶的元素等方法。
思路
在数组中用一个start指向当前队列头的位置,出队列就往上添加;用一个元素end表示队列尾的位置,入队列就往上添加。
代码
public class ArrayQueue {
public static void main(String[] args){
ArrayQueue queue=new ArrayQueue(3);
queue.push(1);
queue.push(3);
queue.push(4);
System.out.println(queue.peek());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
// System.out.println(queue.pop());
}
private int[] arr;
private int start;
private int end;
private int size;
public ArrayQueue(int initSize){
if(initSize<0){
throw new IllegalArgumentException("initSize must more than 0");
}
arr=new int[initSize];
start=0;
end=0;
size=0;
}
public Integer peek(){
if(size==0){
return null;
}
return arr[start];
}
public void push(int val){
if(size==arr.length){
throw new ArrayIndexOutOfBoundsException("The queue is full");
}
size++;
arr[end]=val;
end=end==arr.length-1?0:end+1;
}
public Integer pop(){
if(size==0){
throw new ArrayIndexOutOfBoundsException("The queue is empty");
}
size--;
int val=arr[start];
start=start==arr.length-1?0:start+1;
return val;
}
}