队列与循环队列的实现

一、 队列在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. 循环队列队头出队,队尾入队别搞混!
    示意图:
全部评论

相关推荐

昨天 16:50
已编辑
长安大学 C++
晓沐咕咕咕:评论区没被女朋友好好对待过的计小将可真多。觉得可惜可以理解,毕竟一线大厂sp。但是骂楼主糊涂的大可不必,说什么会被社会毒打更是丢人。女朋友体制内生活有保障,读研女朋友还供着,都准备订婚了人家两情相悦,二线本地以后两口子日子美滋滋,哪轮到你一个一线城市房子都买不起的996清高计小将在这说人家傻😅
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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