package 集合.Stack;
import java.util.Arrays;
import java.util.EmptyStackException;
import java.util.Vector;
public class MyStack {
//底层数组默认长度为10
private Object[] myStack = new Object[10];
//size
private int size = 0;
public MyStack() {
}
//push
public Object push(Object obj) {
//先判断是否需要扩容
if(size>=myStack.length){
myStack = Arrays.copyOf(myStack,myStack.length*2);
}
//添加元素
myStack[size++] = obj;
//size++;
return obj;
}
//pop弹出栈顶元素
public Object pop() {
Object obj = peek();
//忽略栈顶元素
size--;
return obj;
}
//peek查找栈顶元素
public Object peek() {
if(empty()){
throw new EmptyStackException();
}
return myStack[size - 1];
}
//empty判断栈是否为空
public boolean empty() {
return size == 0;
}
//search查找栈中第一出线的元素
public int search(Object obj) {
for(int i = size -1,j=1;i>=0;i--,j++){
if(myStack[i] == obj||myStack[i]!=null&&myStack[i].equals(obj)){
return j;
}
}
return -1;
}
@Override
public String toString() {
Object[] strstack = new Object[size];
System.arraycopy(myStack,0,strstack,0,size);
for(int i=size-1;i>=size/2;i--){
Object temp = strstack[i];
strstack[i] = strstack[size-i-1];
strstack[size-i-1] = temp;
}
return Arrays.toString(strstack);
}
}