zoukankan      html  css  js  c++  java
  • 用数组实现循环队列

    数组实现循环队列
    public class ArrayQueue {
    public Integer arr[];
    public Integer start; //删除时start指针向前走一步。
    public Integer end; //插入时end指针向前走一步。
    public int size; //size只和array.length进行比较,目的是确定这个队列是否满了
    public ArrayQueue(int initsize){ //数组初始化。
    arr = new Integer[initsize];
    start = 0;
    end = 0;
    size = 0;
    }
    public void push(int number){
    if (size==arr.length){ //此时队列已满。
    throw new ArrayIndexOutOfBoundsException("the Queue is full");
    }
    size++; //添加元素时size++;
    arr[end] = number;
    end = end==size-1?0:end+1; //判断是否达到了最火一个位置,如果达到了,则回到第一个位置。
    }
    public Integer poll(){
    if (size==0){
    throw new ArrayIndexOutOfBoundsException("the Queue is empty");
    }
    size--; //删除元素时size--;
    int temp = start; //保留删除元素的索引,方便返回用。
    start = start==size-1?0:start+1;
    return arr[temp];
    }
    }
    总结:1,因为是循环队列,所以加了一个size进行变量,每次添加元素时和arr.length进行判断。
    2,使用双指针进行操作。
    3,当指针到达末尾时,回到0位置。
  • 相关阅读:
    搭建vue开发环境的步骤
    widow怎么结束某端口占用
    替换数据库表中某个代码段中某个字段的某一段字符串sql
    sql优化
    scssmap对象访问
    IntelliJ IDEA 和 webstorm更换主题
    css滚动条样式
    redis set
    【LeetCode】128. 最长连续序列
    第二章 模型评估
  • 原文地址:https://www.cnblogs.com/liuwentao/p/9358011.html
Copyright © 2011-2022 走看看