美文网首页
经典例题:模仿栈

经典例题:模仿栈

作者: 是归人不是过客 | 来源:发表于2020-09-16 22:38 被阅读0次

    测试类:

    class Test {
        public static void main(String[] args) throws StackOperationException{
            Stack st = new Stack();
            try {
                st.push(new User("hl",1));
                st.push(new User("hf",2));
                st.push(new User("yx",3));
                st.push(new User("hx",4));
                st.push(new User("ll",5));
            }catch(Exception e) {
                e.printStackTrace();
            }
            try {
                System.out.println(st.pop());
                System.out.println(st.pop());
                System.out.println(st.pop());
                System.out.println(st.pop());
                System.out.println(st.pop());
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    栈类:

    class Stack{
        Object[] elements;
        int index;
        Stack(){
            this(5);
        }
        Stack(int max){
            elements = new Object[max];
        }
        public void push(Object element) throws StackOperationException {
            if(index == elements.length) {
                throw new StackOperationException("越栈");
            }
            else {
                elements[index++] = element;
            }
            
        }
        public Object pop() throws StackOperationException {
            if(index == 0) {
                throw new StackOperationException("栈空");
            }
            else {
                Object element = elements[--index];
                return element;
            }
        }
    }
    

    自定义异常:

    class StackOperationException extends Exception{
        
        public StackOperationException() {}
        
        public StackOperationException(String msg) {
            
            super (msg);
        }
    }
    

    添加用户类:

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

    相关文章

      网友评论

          本文标题:经典例题:模仿栈

          本文链接:https://www.haomeiwen.com/subject/ishkyktx.html