数组实现栈和队列

170 阅读1分钟

数组实现栈

public static class ArrayStack{
        private Integer[] arr;
        private Integer size;
        public ArrayStack(int initsize){
            if(initsize < 0){
                throw new IllegalArgumentException("this init size is less than 0");
            }
            arr = new Integer[initsize];
            size = 0;
        }
        public Integer peek(){
            if(size == 0){
                return null;
            }
            return arr[size-1];
        }
        public void push(int obj){
            if(size == arr.length){
                throw new ArrayIndexOutOfBoundsException("this stack is full");
            }
            arr[size++] = obj;
        }
        public Integer pop(){
        	if(size == 0){
                throw new ArrayIndexOutOfBoundsException("this stack is empty");
            }
            return arr[--size];
        }

    }

数组实现队列

public static class ArrayQueen{
        private Integer[] arr;
        private Integer size;
        private Integer first;
        private Integer last;
        public ArrayQueen(int initsize){
            if(size < 0){
                throw new IllegalArgumentException("the initsize less than 0 ");
            }
            arr = new Integer[initsize];
            size = 0;
            first = 0;
            last = 0;
        }
        public Integer peek(){
            if(size == 0){
                return null;
            }
            return arr[first];
        }
        public void push(int num){
            if(size == arr.length){
                throw new ArrayIndexOutOfBoundsException("the queen is full");
            }
            size++;
            arr[last] = num;
            last = last == arr.length - 1 ? 0 : last + 1;
        }
        public Integer poll(){
            if(size == 0){
                throw new ArrayIndexOutOfBoundsException("the queen is empty");
            }
            size--;
            int temp = first;
            first = first == arr.length - 1 ? 0 : first + 1;
            return arr[temp];
        }
    }