Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".

One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.

Your implementation should support following operations:

  • MyCircularQueue(k): Constructor, set the size of the queue to be k.
  • Front: Get the front item from the queue. If the queue is empty, return -1.
  • Rear: Get the last item from the queue. If the queue is empty, return -1.
  • enQueue(value): Insert an element into the circular queue. Return true if the operation is successful.
  • deQueue(): Delete an element from the circular queue. Return true if the operation is successful.
  • isEmpty(): Checks whether the circular queue is empty or not.
  • isFull(): Checks whether the circular queue is full or not.

Example:

  1. MyCircularQueue circularQueue = new MyCircularQueue(3); // set the size to be 3
  2. circularQueue.enQueue(1);  // return true
  3. circularQueue.enQueue(2);  // return true
  4. circularQueue.enQueue(3);  // return true
  5. circularQueue.enQueue(4);  // return false, the queue is full
  6. circularQueue.Rear();  // return 3
  7. circularQueue.isFull();  // return true
  8. circularQueue.deQueue();  // return true
  9. circularQueue.enQueue(4);  // return true
  10. circularQueue.Rear();  // return 4

Note:

  • All values will be in the range of [0, 1000].
  • The number of operations will be in the range of [1, 1000].
  • Please do not use the built-in Queue library.

设计一个环形队列,包含以下几个操作功能:设置队列大小,获取前一个元素,获取最后一个元素,插入一个元素,删除一个元素,判断队列是否满了,判断队列是否为空。不能用内置的Queue函数库。

解法:数组

Java:

  1. class MyCircularQueue {
  2. final int[] a;
  3. int front, rear = -1, len = 0;
  4.  
  5. public MyCircularQueue(int k) { a = new int[k];}
  6.  
  7. public boolean enQueue(int val) {
  8. if (!isFull()) {
  9. rear = (rear + 1) % a.length;
  10. a[rear] = val;
  11. len++;
  12. return true;
  13. } else return false;
  14. }
  15.  
  16. public boolean deQueue() {
  17. if (!isEmpty()) {
  18. front = (front + 1) % a.length;
  19. len--;
  20. return true;
  21. } else return false;
  22. }
  23.  
  24. public int Front() { return isEmpty() ? -1 : a[front];}
  25.  
  26. public int Rear() {return isEmpty() ? -1 : a[rear];}
  27.  
  28. public boolean isEmpty() { return len == 0;}
  29.  
  30. public boolean isFull() { return len == a.length;}
  31. }  

Python:

  1. class Node:
  2. def __init__(self, value):
  3. self.val = value
  4. self.next = self.pre = None
  5. class MyCircularQueue:
  6.  
  7. def __init__(self, k):
  8. self.size = k
  9. self.curSize = 0
  10. self.head = self.tail = Node(-1)
  11. self.head.next = self.tail
  12. self.tail.pre = self.head
  13.  
  14. def enQueue(self, value):
  15. if self.curSize < self.size:
  16. node = Node(value)
  17. node.pre = self.tail.pre
  18. node.next = self.tail
  19. node.pre.next = node.next.pre = node
  20. self.curSize += 1
  21. return True
  22. return False
  23.  
  24. def deQueue(self):
  25. if self.curSize > 0:
  26. node = self.head.next
  27. node.pre.next = node.next
  28. node.next.pre = node.pre
  29. self.curSize -= 1
  30. return True
  31. return False
  32.  
  33. def Front(self):
  34. return self.head.next.val
  35.  
  36. def Rear(self):
  37. return self.tail.pre.val
  38.  
  39. def isEmpty(self):
  40. return self.curSize == 0
  41.  
  42. def isFull(self):
  43. return self.curSize == self.size  

C++:

  1. class MyCircularQueue {
  2. public:
  3. /** Initialize your data structure here. Set the size of the queue to be k. */
  4. MyCircularQueue(int k) {
  5. data.resize(k);
  6. head = 0;
  7. tail = 0;
  8. reset = true;
  9. }
  10.  
  11. /** Insert an element into the circular queue. Return true if the operation is successful. */
  12. bool enQueue(int value) {
  13. if (isFull()) return false;
  14. // update the reset value when first enqueue happens
  15. if (head == tail && reset) reset = false;
  16. data[tail] = value;
  17. tail = (tail + 1) % data.size();
  18. return true;
  19. }
  20.  
  21. /** Delete an element from the circular queue. Return true if the operation is successful. */
  22. bool deQueue() {
  23. if (isEmpty()) return false;
  24. head = (head + 1) % data.size();
  25. // update the reset value when last dequeue happens
  26. if (head == tail && !reset) reset = true;
  27. return true;
  28. }
  29.  
  30. /** Get the front item from the queue. */
  31. int Front() {
  32. if (isEmpty()) return -1;
  33. return data[head];
  34. }
  35.  
  36. /** Get the last item from the queue. */
  37. int Rear() {
  38. if (isEmpty()) return -1;
  39. return data[(tail + data.size() - 1) % data.size()];
  40. }
  41.  
  42. /** Checks whether the circular queue is empty or not. */
  43. bool isEmpty() {
  44. if (tail == head && reset) return true;
  45. return false;
  46. }
  47.  
  48. /** Checks whether the circular queue is full or not. */
  49. bool isFull() {
  50. if (tail == head && !reset) return true;
  51. return false;
  52. }
  53. private:
  54. vector<int> data;
  55. int head;
  56. int tail;
  57. // reset is the mark when the queue is empty
  58. // to differentiate from queue is full
  59. // because in both conditions (tail == head) stands
  60. bool reset;
  61. };
  62.  
  63. /**
  64. * Your MyCircularQueue object will be instantiated and called as such:
  65. * MyCircularQueue obj = new MyCircularQueue(k);
  66. * bool param_1 = obj.enQueue(value);
  67. * bool param_2 = obj.deQueue();
  68. * int param_3 = obj.Front();
  69. * int param_4 = obj.Rear();
  70. * bool param_5 = obj.isEmpty();
  71. * bool param_6 = obj.isFull();
  72. */

类似题目:

[LeetCode] 641.Design Circular Deque 设计环形双向队列  

All LeetCode Questions List 题目汇总

[LeetCode] 622.Design Circular Queue 设计环形队列的更多相关文章

  1. [LeetCode] Design Circular Queue 设计环形队列

    Design your implementation of the circular queue. The circular queue is a linear data structure in w ...

  2. [LeetCode] 641.Design Circular Deque 设计环形双向队列

    Design your implementation of the circular double-ended queue (deque). Your implementation should su ...

  3. Leetcode622.Design Circular Queue设计循环队列

    设计你的循环队列实现. 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环.它也被称为"环形缓冲器". 循环队列的一个好处是 ...

  4. LeetCode 622. Design Circular Queue

    原题链接在这里:https://leetcode.com/problems/design-circular-queue/ 题目: Design your implementation of the c ...

  5. [LeetCode] Design Circular Deque 设计环形双向队列

    Design your implementation of the circular double-ended queue (deque). Your implementation should su ...

  6. 【LeetCode】622. Design Circular Queue 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 用直的代替弯的 数组循环利用 日期 题目地址:htt ...

  7. 【leetcode】622. Design Circular Queue

    题目如下: Design your implementation of the circular queue. The circular queue is a linear data structur ...

  8. LeetCode 622:设计循环队列 Design Circular Queue

    LeetCode 622:设计循环队列 Design Circular Queue 首先来看看队列这种数据结构: 队列:先入先出的数据结构 在 FIFO 数据结构中,将首先处理添加到队列中的第一个元素 ...

  9. LeetCode 641. Design Circular Deque

    原题链接在这里:https://leetcode.com/problems/design-circular-deque/ 题目: Design your implementation of the c ...

随机推荐

  1. RabbitMQ 部署记录

    1. erlang与rabbitmq版本对应关系: https://www.rabbitmq.com/which-erlang.html 2. 安装erlang 下载地址:http://www.erl ...

  2. keil中error: #70: incomplete type is not allowed—解决方法

    今天在写程序的时候,想使用sizeof求数组的大小,数组中其他c文件定义,在头文件使用extern uint8_t buff_value[]; 声明 但是keil编译报错,网上查了,发现,需要写成ex ...

  3. How do I fix "selector not recognized" runtime exceptions when trying to use category methods from a static library?

    https://developer.apple.com/library/content/qa/qa1490/_index.html A: If you're seeing a "select ...

  4. NSKeyedArchiver : NSCoder

    NSKeyedArchiver : NSCoder @interface NSData : NSObject <NSCopying, NSMutableCopying, NSSecureCodi ...

  5. Markdown&Latex学习笔记,qwq

    目录 推荐的文章 居中 字体 加颜色 指数 分数 根号 神奇的符号(不要多想qwq) 箭头 小于号 大括号 累加符号 累乘符号 下标 \(\phi\)&\(\varphi\) \(\equiv ...

  6. 使用apt-mirror搭建debian镜像源

    debian官方提供了脚本ftpsync来搭建源镜像,而 apt-mirror 是一个更简单便捷的源镜像搭建工具. 安装 apt-mirror sudo apt-get install apt-mir ...

  7. Ubuntu 16.04 一系列软件安装命令,包括QQ、搜狗、Chrome、vlc、网易云音乐安装方法

    1 简介 Ubuntu 16.04安装完后,还需要做一些配置才能愉快的使用,包括添加软件源.安装搜狗输入法.Chrome浏览器.网易云音乐.配置快捷键.安装git等等,下面就跟着我来配置吧,just ...

  8. <每日 1 OJ> -24. The Simple Problem

    题目描述 Solo上了大学,对数学很感兴趣,有一天他面对数分三,一个Sequence(数列)摆在了他面前,这可难住他了……序列如下:S(a,k,n)=a+(k+a)+(2k+a)+…+(nk+a),题 ...

  9. html内获取当前文件路径,页面获取当前路径

    function getRealPath(){ var curWwwPath = window.document.location.href; var pathName = window.docume ...

  10. zabbix 自动发现 监控 硬盘读写 disk io

    直接 上配置: 1.配置文件 cat userparameter_harddisk.conf #discovery hard diskUserParameter=custom.vfs.discover ...