模拟栈弹出

 


package qlianxi;

//第一题:栈--后进先出

public class AStack {

//第一步
//使用数组可以存储数据 //栈可以存储多个引用类型的元素 Object[] elements; //指向栈顶元素上方的一个帧 int index; //默认为0 //栈默认的初始化容量是5 //Constructor AStack(){ this(4); //不这样写elements = new Object[max],用this是为了代码重用 } AStack(int max){ elements = new Object[max]; }
//第二步
//栈应该对外提供一个压栈的方法 public void push(Object element) throws StackOperationException{ if(index == elements.length){ //异常 throw new StackOperationException("栈已满"); } /* elements[index] = elements; index++; */ //简化版 elements[index++] = element; //先赋值,然后才会++ }
//第三步
//栈应该对外提供一个弹栈的方法 public Object pop() throws StackOperationException{ //栈顶的元素往外弹 if(index == 0){ throw new StackOperationException("栈已空!"); } /* index--; return elements[index]; */ return elements[--index]; //因为索引从零开始,要把指针下移一位才能弹,因为上面设定的是指向栈顶元素上方的一个帧 } }

 

public class ATest {

    public static void main(String[] args) {

        AStack s = new AStack();
        
        AUser u1 = new AUser("A",20);
        AUser u2 = new AUser("B",21);
        AUser u3 = new AUser("C",22);
        AUser u4 = new AUser("D",23);
        AUser u5 = new AUser("E",24);
        AUser u6 = new AUser("F",25);
        

        try{
            s.push(u1);
            s.push(u2);
            s.push(u3);
            s.push(u4);
            s.push(u5);
            
            s.push(u6);
        }catch(StackOperationException e){
            e.printStackTrace();
        }
        
        try{
            //
            System.out.println(s.pop());
            System.out.println(s.pop());
            System.out.println(s.pop());
            System.out.println(s.pop());
            System.out.println(s.pop());
            
            System.out.println(s.pop());
        }catch(StackOperationException e){
            e.printStackTrace();
        }
    }
}

 

 

package qlianxi;

public class AUser {

    String name;
    int age;
    
    AUser(String name, int age){
        this.name = name;
        this.age = age;
    }
    
    public String toString(){
        return "User[name="+name+",age="+age+"]";
    }
}

 

package qlianxi;

public class StackOperationException extends Exception{

    //编写超出压栈数量异常
    public StackOperationException(){}
    public StackOperationException(String msg){
        super(msg);
    }
}

 

posted @ 2020-08-13 23:34  Lerresino  阅读(111)  评论(0)    收藏  举报