队列与循环队列的实现

一、 队列在Java中可以直接使用库函数,
Queue< Integer> queue = new LinkList<>();
这样便建立了一个链表构成的队列,元素类型为Integer。
主要操作有:
queue.peek()获取队头元素(要删也是它第一个被删);
queue.offer(x)入队操作push;
queue.pop()队头出队操作;
queue.remove()队头出队并赋值给返回值;
queue.size()获取队列长度。

二、 循环队列需要自己实现数据结构:
题目:

设计一个循环队列
leetcode:https://leetcode-cn.com/problems/design-circular-queue

如果采用直接模拟的方法,光是进队的判断就多达5个,写5个if?逻辑会像下面这样混乱:

循环队列直接模拟

题解里说,使用较少的变量可以减少冗(rong)余,太少会提高时间复杂度(越少的变量,逻辑越复杂)。
为了减少队尾指针(增加队列元素所用),需要用一个公式:

队尾 = (队头+队列长度 -1 )% 数组长度

判断队列满可以用cout变量(队列长度),初始化为0,只要进队了一个元素(headIndex),cout就加1,加到等于数组长度的数值时就队列满;出队只要cout为正数,按照上面的公式计算出队尾的位置,将值赋给它即可。
cout==0 队列空,cout=数组长度 队列满。

官方题解:
class MyCircularQueue {

  private int[] queue;
  private int headIndex;
  private int count;
  private int capacity;

  /** Initialize your data structure here. Set the size of the queue to be k. */
  public MyCircularQueue(int k) {
    this.capacity = k;
    this.queue = new int[k];
    this.headIndex = 0;
    this.count = 0;
  }

  /** 入队,是队尾位置加1的位置作为新入队的元素位置,队尾指针原本是有队列元素的。
      Insert an element into the circular queue. Return true if the operation is successful.         
  */
  public boolean enQueue(int value) {
    if (this.count == this.capacity)
      return false;
    this.count += 1;
    this.queue[(this.headIndex + this.count - 1) % this.capacity] = value;
    return true;
  }

  /** 出队是直接对头指针加一,结果取模数就行。
      Delete an element from the circular queue. Return true if the operation is successful. 
  */
  public boolean deQueue() {
    if (this.count == 0)
      return false;
    this.headIndex = (this.headIndex + 1) % this.capacity;
    this.count -= 1;
    return true;
  }

  /** Get the front item from the queue. */
  public int Front() {
    if (this.count == 0)
      return -1;
    return this.queue[this.headIndex];
  }

  /** Get the last item from the queue. */
  public int Rear() {
    if (this.count == 0)
      return -1;
    int tailIndex = (this.headIndex + this.count - 1) % this.capacity;//队尾 = (队头+队列长度 -1 )% 数组长度
    return this.queue[tailIndex];
  }

  /** Checks whether the circular queue is empty or not. */
  public boolean isEmpty() {
    return (this.count == 0);
  }

  /** Checks whether the circular queue is full or not. */
  public boolean isFull() {
    return (this.count == this.capacity);
  }
}

注意事项:

  1. 队尾 = (队头+队列长度 -1 )% 数组长度得出的是当前队尾,是原本就有队列元素的,要队尾入队必须将cout队列长度先+1,否则会覆盖原本的队尾元素!
  2. 循环队列队头出队,队尾入队别搞混!
    示意图:
全部评论

相关推荐

HR_丸山彩同学:你的项目描述里,系统设计讲了很多:MemCube是什么、三级存储架构怎么设计、四种遗忘策略分别是什么。这些面试的时候讲没问题,但简历上不需要这么细。 简历要突出的是影响力,不是实现细节。面试官看简历的时候想知道的是「这个项目有多大价值」,不是「这个项目具体怎么实现的」。实现细节是面试时候聊的 怎么改:技术细节可以精简为一句「采用三级存储架构+四种遗忘策略」,把省出来的篇幅用来写影响力。比如:项目有没有开源?有没有写成技术博客?有没有被别人使用过? 校园经历没有任何信息量,任何人都可以写这句话,写了等于没写。更关键的是,你投的是技术岗,校园活动经历本来就不是加分项。如果非要写,必须写出具体的数字和成果。如果你没有这些数字,那就老老实实删掉 「端到端耗时缩减30-40%」要给出确切数字和绝对值。从1000ms降到600ms是降了40%,从100ms降到60ms也是降了40%,但这两个含义完全不一样。其他也是,涉及到数据,准备好证据,口径统一,面试会问 「熟练」「熟悉」「了解」混在一起用,读起来很乱。而且「了解前端需求」最好改成「具备前后端协作经验」
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务