Java用数组实现栈

import java.util.Arrays;
import java.util.EmptyStackException;
import java.util.Stack;

public class MyStack  {

    private Object[] myStack = new Object[10];
    private int size = 0;

    public MyStack() {

    }

    public  Object push(Object obj){

        if(size >= myStack.length){
            myStack = Arrays.copyOf(myStack,myStack.length*2);
        }
        //添加元素
        myStack[size++] = obj;
        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;
    }
}

 

posted @ 2021-04-12 10:04  Code_Dog  Views(176)  Comments(0Edit  收藏  举报