【编程题】用数组实现栈(Java实现)
题目描述
通过一个数组实现栈的功能,具有出栈、压栈、计算当前栈的元素值、以及栈的大小等方法。
思路
在数组中用一个index指向当前元素的位置,压栈就往上添加,出栈就往下减少,元素个数即当前位置到开始位置个数,栈的大小为数组的大小。
代码
package niuke;
public class ArrayStack {
public static void main(String[] args){
ArrayStack stack=new ArrayStack(3);
stack.push(1);
stack.push(3);
stack.push(4);
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
// System.out.println(queue.pop());
}
private Integer arr[];
private Integer index;
public ArrayStack(int initSize){
if(initSize<0){
throw new IllegalArgumentException("initSize must more than 0");
}
arr=new Integer[initSize];
index=0;
}
public Integer peek(){
if(index==0)
return null;
return arr[index-1];
}
public void push(int val){
if(index==arr.length){
throw new ArrayIndexOutOfBoundsException("The stack is full");
}
arr[index++]=val;
}
public Integer pop(){
if(index==0){
throw new ArrayIndexOutOfBoundsException("The stack is empty");
}
return arr[--index];
}
}