JAVA一维数组模拟栈

package 模拟栈;

public class moni {
    
    
    public static void main(String[] args) {
    
    
        moni stack = new moni();
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        stack.push(new Object());
        //加满
        stack.push(new Object());
        for (int i = 0; i < 10; i++) {
    
    
            System.out.println(stack.pop());
        }
        /*stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();*/

    }

    private Object[] elements;
    private int index;
    public moni() {
    
    
        this.elements = new Object[10];
        this.index = -1;
    }
    public void push(Object obj){
    
    
        if(this.index>=this.elements.length-1){
    
    
            System.out.println("栈满");
            return ;
        }
        this.index++;
        this.elements[index] = obj;
        System.out.println("成功 index = "+index);
    }
    public Object  pop(){
    
    
        if(index == -1){
    
    
            System.out.println("栈空");
            return -1;
        }

//        System.out.print("弹栈" + " " + elements[index] + "元素成功,");
//         栈帧向下移动一位。
        return elements[index--];
//        System.out.println("栈帧指向" + index);
//        return index;
    }


    public Object[] getElements() {
    
    
        return elements;
    }

    public void setElements(Object[] elements) {
    
    
        this.elements = elements;
    }
}

おすすめ

転載: blog.csdn.net/m0_46381590/article/details/118861394