数组实现栈

用数组实现栈
public class ArrayStack {
Integer arr[];
Integer size ;
public ArrayStack(int initsize){ //对数组进行初始化,即对栈进行初始化
if(initsize<0)
throw new IllegalArgumentException("the init size less than 0");
arr = new Integer[initsize];
size = 0;
}
public void push(int number){ //push操作,每次添加一个元素,则在数组最后一个位置添加元素。
if(size==arr.length){
throw new ArrayIndexOutOfBoundsException("the stack is full");
}
arr[size++] = number;
}
public Integer pop(){ //pop操作,每次弹出最后一个元素,同时size减一。
if(size==0){
throw new ArrayIndexOutOfBoundsException("the stack is empty");
}
return arr[--size];
}
public Integer peek(){ //对于栈是显示最上面的元素,对于数组是显示最后一个元素。
if(size==0){
return null;
}
return arr[size-1];
}
}
总结:使用数组,控制好临界条件,栈为后进先出。
原文地址:https://www.cnblogs.com/liuwentao/p/9357999.html