栈的特点:先进后出
栈常用的方法:
stack.pop() //出栈
stack.peek() //查看栈顶元素
stack.push() //入栈
stack.isEmpty() //判断栈是否为空
使用数组实现栈注意事项:
1.在入栈的时候要进行数组扩容;这里还有一个注意事项就是因为使用的是int类型数据,考虑int溢出的情况,目前这里代码没有实现
代码如下:
public class MyStack <T>{
private Object[] stack;
private int top;
public MyStack() {
this.stack = new Object[10];
}
public boolean isEmpty() {
return this.top==0;
}
public void push(T t){
expandCapacity(top+1);
stack[top] = t;
top++;
}
public T peek(){
if (top>0){
return (T) stack[top-1];
}
throw new RuntimeException("Stack overflow");
}
public T pop() {
if (top>0){
T peek = peek();
stack=null;
return peek;
}
throw new RuntimeException("Stack overflow");
}
public void expandCapacity(int newSize){
int len = stack.length;
if (newSize>len){
//进行扩容
len+=len/2;
stack = Arrays.copyOf(stack, len);
}
}
}