数组实现队列

package class01;

/**
 * @author chencc
 * @Description 数组实现队列
 * @Date 2022/3/16 13:50
 */
public class RingArray {

    //构建一个队列(内部实现是数组)
    public static class MyQueue {
        private int[] arr;
        private int begin;
        private int end;
        private int size;
        private final int limit;

        //构造器(初始化)
        public MyQueue(int limit) {
            //初始化limit大小的空数组
            arr = new int[limit];
            //开始指针
            begin = 0;
            //结尾指针
            end = 0;
            //数组大小
            size = 0;
            this.limit = limit;
        }

        //插入数据
        public void push(int value) {
            //判断数组是否满了
            if (size == limit) {
                throw new RuntimeException("队列已满");
            }
            //将当前数加入到数组end位置
            arr[end] = value;
            //数组大小+1
            size++;
            //判断end的指针位置
            end = nextIndex(end);
        }

        //弹出数据
        public int pop() {
            if (size == 0) {
                throw new RuntimeException("队列空了");
            }
            //取出数组begin职位的数
            int ans = arr[begin];
            //数组大小-1
            size--;
            //判断begin的指针位置
            begin = nextIndex(begin);
            return ans;
        }

        private int nextIndex(int i) {
            return i < limit - 1 ? i + 1 : 0;
        }
    }

    public static void main(String[] args) {
        MyQueue queue = new MyQueue(5);
        queue.push(3);
        queue.push(2);
        queue.push(1);
        queue.push(4);
        queue.push(8);
        System.out.println("=====================");
        System.out.println(queue.pop());

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值