public class MyStack {
// 一个栈
int[] elements;
public MyStack(){
elements = new int[0];
}
// 进栈
public void push(int element){
// 扩大数组,并把数据放在最后
int[] newArr = new int[elements.length+1];
for (int i = 0; i < elements.length; i++) {
newArr[i] = elements[i];
}
newArr[elements.length] = element;
elements = newArr;
}
// 出栈
public int pop(){
// 如果栈为空抛出异常
if(elements.length == 0){
throw new RuntimeException("stack is empty");
}
// 缩容--把数据去掉一位
int element = elements[elements.length-1];
int []newArr = new int[elements.length-1];
for (int i = 0; i < elements.length-1; i++) {
newArr[i] = elements[i];
}
elements = newArr;
return element;
}
// 回复栈的位数
public int peek(){
return elements[elements.length-1];
}
public boolean isEmpty(){
return elements.length == 0;
}
}