用数组结构实现大小固定的队列和栈

package basic_class_03;
/**
 * 数组实现栈跟队列
 * @author lenovo
 *
 */
public class Code_01_Array_To_Stack_Queue_1 {

    /**
     * 队列是先进后出
     * 所以获取元素的指针只需要size就行
     * @author lenovo
     *
     */
    public static class ArrayStack {
        private Integer[] arr;
        private Integer size;
        public ArrayStack(int initSize) {
            if(initSize < 0) {
                throw new IllegalArgumentException("The init size is less then 0 ");
            }
            arr = new Integer[initSize];
            size = 0;
        }


        public void push(int obj) {
            if(size == arr.length) {
                throw new ArrayIndexOutOfBoundsException("The queue is full");
            }
            arr[size++] = obj;
        }


        public Integer peek() {
            if(size == 0) {
                return null;
            }
            return arr[size - 1];  // size 的长度并没有改变
        }


        public Integer pop() {
            if(size == 0) {
                throw new ArrayIndexOutOfBoundsException("The queue is empty ");
            }
            return arr[--size];  // 是从数组后面往前放元素
        }
    }

    /**
     * 设计的时候获取元素的时候 别用循环  底层代码最好使用指针 而不是用循环
     * @author lenovo
     *
     */
    public static class ArrayQueue {
        private Integer[] arr;
        private Integer size;
        private Integer first;   // 这个指针是用来取元素的   当元素取完了,可以设置为 0 
        private Integer last;    // 这个指针是用来放元素的   当元素放完了,可以设置为0


        public ArrayQueue(int initSize) {
            if(initSize < 0) {
                throw new IllegalArgumentException("The init size is less then 0");
            }
            arr = new Integer[initSize];
            size = 0;
            first = 0;
            last = 0;
        }



        public void push(int obj) {
            if(size == arr.length) {
                throw new ArrayIndexOutOfBoundsException("The Queue is full");
            }
            size++;
            arr[last] = obj;
            last = last == arr.length - 1 ? 0 : last + 1;  
        }


        public Integer poll() {
            if(size == 0) {
                throw new ArrayIndexOutOfBoundsException("The queue is empty");
            }
            size--;
            int tmp = first;
            first = first == arr.length -1 ? 0 : first + 1;
            return arr[tmp];  // 获取的是先放进去的元素
        }

    }



}

猜你喜欢

转载自blog.csdn.net/qq_38200548/article/details/81268412