首页 > 其他分享 >使用数组实现队列。(有图)

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

时间:2022-11-03 00:13:16浏览次数:43  
标签:有图 队列 private int limit 数组 public size

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;
        }

    }
}

 

 

标签:有图,队列,private,int,limit,数组,public,size
From: https://www.cnblogs.com/TheFloorIsNotTooHot/p/16853010.html

相关文章