使用数组实现队列。(有图)

package class03;

/**
 * 使用数组实现队列
 * 先进先出
 */
public class Code04_RingArray {

    public class MyQueue {
        private int pushIndex;//下一个要添加的元素的索引位置。
        private int pollIndex;//下一个要弹出的元素的索引位置。
        private int size;//目前队列中一共有几个数。重要参数。队列还能不能添加数,还能不能弹出数,就靠它管着。
        private int[] arr;
        private final int limit;//数组长度。

        public MyQueue(int limit) {
            arr = new int[limit];
            pushIndex = 0;
            pollIndex = 0;
            size = 0;
            this.limit = limit;
        }

        //添加元素
        public void push(int value) {
            if (size == limit) {
                throw new RuntimeException("队列已满,不能再添加值了!");
            }
            size++;
            arr[pushIndex] = value;
            pushIndex = nextIndex(pushIndex);
        }

        //弹出元素
        public int poll() {
            if (size == 0) {
                throw new RuntimeException("队列已空,不能再取值了!");
            }
            size--;
            int num = arr[pollIndex];
            pollIndex = nextIndex(pollIndex);
            return num;
        }

        public boolean isEmpty() {
            return size == 0;
        }

        //返回当前下标i的下一个下标
        private int nextIndex(int i) {
            return i < limit - 1 ? i + 1 : 0;
        }

    }
}

 

 

posted @ 2022-11-02 23:57  TheFloorIsNotTooHot  阅读(35)  评论(0)    收藏  举报