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); } }