Stack接口:
public interface MyStack {
//进栈
Object push(Object s);
//出栈
Object pop();
//判断空
boolean isEmpty();
//查看栈顶元素
Object peek();
}
stack接口实现类
public class MyStackImpl implements MyStack {
private int top = -1; //栈顶
private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8;
private static final int DEFAULT_CAPACITY = 10;
private Object[] objs;
public MyStackImpl() {
this(DEFAULT_CAPACITY);
}
public MyStackImpl(int capacity) {
if (capacity < 0 || capacity > MAX_CAPACITY) {
throw new IllegalArgumentException("capacity=" + capacity);
}
objs = new Object[capacity];
}
@Override
public Object push(Object obj) {
if(top == objs.length - 1){
this.grow();
}
return objs[++top]=obj;
}
private void grow(){ //扩容
objs = Arrays.copyOf(objs, objs.length + (objs.length>>1));
}
@Override
public Object pop() {
if(isEmpty())
throw new NullPointerException("Stack is empty!");
return objs[top--];
}
@Override
public boolean isEmpty() {
if (top==-1) {
return true;
}else{
return false;
}
}
@Override
public Object peek() {
if (isEmpty()){
throw new EmptyStackException();
}else{
return objs[top];
}
}
}