zoukankan      html  css  js  c++  java
  • 一维数组模拟数据结构-------栈

    1、用一维数据模拟栈结构

    public class Stack1{
        
        //一维数据模拟栈结构
        Object[] elements;
        
        
        //默认栈的容量为5
        public Stack1(){
            this(5);    //this 这里是代码的重用,也可以写成 elements = new Object[5];
                         
        }
        
        public Stack1(int max){
            elements = new Object[max];
        }
        
        //模拟栈指针
        int index;
        
        //压栈方法
        public void push(Object element) throws Stack1OperationException{
            if(index == elements.length){
                throw new Stack1OperationException("The Stack1 have been Full");
            }
            elements[index++] = element;
        }
        
        //弹栈方法
        public  Object pop() throws Stack1OperationException{
            if(index == 0){
                throw new Stack1OperationException("The Stack1 have been Empty!");
            }
            return elements[--index];
        }
        
        
    }

    2、自定义栈异常类

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

    3、测试

    public class TestStack1{
        public static void main(String[] args){
            Stack1 s = new Stack1();
            User u1 = new User("Jack",23);
            User u2 = new User("Ford",24);
            User u3 = new User("King",25);
            User u4 = new User("Smith",26);
            User u5 = new User("COOK",27);
            User u6 = new User("zhangsan",28);
            try{
                s.push(u1);
                s.push(u2);
                s.push(u3);
                s.push(u4);
                s.push(u5);
                s.push(u6);
            }catch(Stack1OperationException 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());
            }catch(Stack1OperationException e){
                e.printStackTrace();
            }
        }
    }
    
    class User{
        String name;
        int age;
        
        User(String name, int age){
            this.name = name;
            this.age = age;
        }
        
        public String toString(){
            return "User[name="+name+" ,age="+age+"]";
        }
    }
  • 相关阅读:
    SPOJ VJudge QTREE
    LCA 在线倍增法 求最近公共祖先
    Codevs 2370 小机房的树
    51Nod-1632-B君的连通
    51Nod--1100-斜率最大
    51Nod-1276-岛屿的数量
    51Nod-1270-数组的最大代价
    poj
    hihocoder Week136 -- 优化延迟
    poj-1035-Spell Checker
  • 原文地址:https://www.cnblogs.com/StanLong/p/7707213.html
Copyright © 2011-2022 走看看