题目
用数组结构实现大小固定的队列和栈
实现栈
public static class ArrayStack {
private Integer[] arr;//栈结构
private Integer size;//栈的长度
public ArrayStack(int initSize) {
if(initSize < 0){
throw new IllegalArgumentException("初始大小不能小于0!");
}
arr = new Integer[initSize];
size = 0;
}
public void push(int obj){//压栈
if(size == arr.length){
throw new IllegalArgumentException("栈已满!");
}
arr[size++] = obj;
}
public Integer peek(){//返回栈顶元素但不弹出
if(size == 0){
return null;
}
return arr[size - 1];
}
public Integer pop(){//弹出栈顶元素
if(size == 0){
throw new IllegalArgumentException("栈已空!");
}
return arr[--size];
}
}
实现队列
public static class ArrayQueue{
private Integer[] arr;
private Integer size,first,last;
public ArrayQueue(int initSize){
if(initSize < 0){
throw new IllegalArgumentException("初始大小不能小于0!");
}
arr = new Integer[initSize];
size = 0;
first = 0;
last = 0;
}
public Integer peek(){
if(size == 0){
return null;
}
return arr[first];
}
public void push(int obj){
if(size == arr.length){
throw new IllegalArgumentException("队列已满!");
}
size++;
arr[last] = obj;
last = (last == arr.length-1) ? 0 : last+1;//达到最大长度后回到起点
}
public Integer poll(){
if(size == 0){
throw new IllegalArgumentException("队列已空!");
}
size--;
int temp = first;
first = (first == arr.length-1) ? 0 : first+1;//达到最大长度后回到起点
return arr[temp];
}
}