算法经典题型 图解分析+代码不能再详细了!——用数组结构实现大小固定的队列

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

分析:

数组队列
这里的数组其实是逻辑上的头尾相连的循环数组,就是循环利用数组
容量固定

其实就是取的指针 start 追着存的指针end跑,可以不设置 size,但是有size判断更方便些,可以把start追着end的逻辑解耦掉。

 

代码:

package Ashier.arithmetic.my_exercise;

/**
 * 用数组结构实现大小固定的队列
 *
 * @author shierS
 * @date 2021/4/2
 */

class ArrayQueue {
    Integer[] arr;
    Integer size = 0;  //队列当前容量
    Integer start = 0; //队列当前头部
    Integer end = 0;  //队列当前尾部

    //初始化队列设置容量大小
    public ArrayQueue(Integer size) {
        if(size < 0){
            throw new IllegalArgumentException("The init size is less than 0");
        }
        arr = new Integer[size];
    }

    //返回第一个传入的元素,但不删除
    public Integer peek() {
        if (size == 0) {
            return null;
        }
        return arr[start];
    }

    //在末尾压入
    public void push(int num) {
        if (size == arr.length) { //队列满了,不能添加了,抛出异常
            throw new ArrayIndexOutOfBoundsException("The queue is full");
        }
        arr[end] = num; //将元素添加到尾部
        size++; //容量++
        end = (end == arr.length - 1) ? 0 : end+1;//判断end是否指向了数组末尾,是的化指回到数组头部
    }

    //弹出头部
    public Integer poll() {
        if (size == 0) { //队列中空了
            throw new ArrayIndexOutOfBoundsException("The queue is empty");
        }
        size--; //容量--
        Integer result = arr[start]; //返回头部元素
        start = (start == arr.length - 1) ? 0 : start+1; //移动start标志
        return result;
    }
}

public class ArrayToQueue {
    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(4);
        arrayQueue.push(1);
        arrayQueue.push(2);
        System.out.println(arrayQueue.peek());
        System.out.println(arrayQueue.poll());
        System.out.println(arrayQueue.peek());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值