Stack: last out
Pankongpanman
push
pop
peek
public class ArrayStack { private Integer index;//把新来的数加入index上 private Integer[] arr; public ArrayStack(int initSize){ if(initSize==0) { throw new IllegalArgumentException("less than 0"); } arr=new Integer[initSize]; } public void push(int a){ if(index==arr.length){ throw new ArrayIndexOutOfBoundsException("栈满") ; } arr[index++]=a; } public Integer pop(){ if(index==0){ throw new ArrayIndexOutOfBoundsException("空栈") ; } return arr[--index]; } public Integer peek(){ if(index==0){ throw new ArrayIndexOutOfBoundsException("空栈") ; } return arr[index-1]; } }
Queue: FIFO
start (size is not 0) to which an unknown number of pick up, start of arr.length-1, and szie = arr.legth;! start zero
end (and about the size, size dissatisfaction) plus, end to arr.length-1, and szie! = arr.legth, end-zero
size: not greater than the length of the array
push (): focus on end and size
poll (): focus on start and size
public class ArrayQueue { private int end; private int start; private int size; private Integer[] arr; public ArrayQueue(int initSize){ if(initSize==0){ throw new IllegalArgumentException("less than 0"); } end=0; start=0; size=0; arr=new Integer[initSize]; } public Integer pop(){ if(size==0){ throw new ArrayIndexOutOfBoundsException("空"); } size--; int ret=start; start=start==arr.length-1?0:start+1; return arr[ret]; } public void push(int a){ if(size==arr.length){ throw new ArrayIndexOutOfBoundsException("队列满"); } arr[end]=a; size++; end=end==arr.length-1?0:end+1; } public int peek(){ if (size==0) throw new ArrayIndexOutOfBoundsException("空"); return arr[start]; } }