• LeetCode-622. 设计循环队列


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

    循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。

    你的实现应该支持如下操作:

    MyCircularQueue(k): 构造器,设置队列长度为 k 。
    Front: 从队首获取元素。如果队列为空,返回 -1 。
    Rear: 获取队尾元素。如果队列为空,返回 -1 。
    enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
    deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
    isEmpty(): 检查循环队列是否为空。
    isFull(): 检查循环队列是否已满。
     

    示例:

    MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
    circularQueue.enQueue(1);  // 返回 true
    circularQueue.enQueue(2);  // 返回 true
    circularQueue.enQueue(3);  // 返回 true
    circularQueue.enQueue(4);  // 返回 false,队列已满
    circularQueue.Rear();  // 返回 3
    circularQueue.isFull();  // 返回 true
    circularQueue.deQueue();  // 返回 true
    circularQueue.enQueue(4);  // 返回 true
    circularQueue.Rear();  // 返回 4
     

    提示:

    所有的值都在 0 至 1000 的范围内;
    操作数将在 1 至 1000 的范围内;
    请不要使用内置的队列库。


     

    1. //
    2. // main.cpp
    3. // 622
    4. //
    5. // Created by Olydebug on 2022/8/5.
    6. //
    7. #include
    8. typedef struct self_queue{
    9. int val;
    10. struct self_queue *next;
    11. struct self_queue *pre;
    12. self_queue(int v):val(v),pre(nullptr),next(nullptr){}
    13. }sq;
    14. class MyCircularQueue {
    15. public:
    16. MyCircularQueue(int k) {
    17. curSize = 0;
    18. maxSize = k;
    19. head = tail = nullptr;
    20. }
    21. bool enQueue(int value) {
    22. if(isFull()){
    23. return false;
    24. }
    25. sq* node = new sq(value);
    26. if (!head) {
    27. head = tail = node;
    28. } else {
    29. tail->next = node;
    30. tail = node;
    31. }
    32. curSize++;
    33. return true;
    34. }
    35. bool deQueue() {
    36. sq* node = head;
    37. if(isEmpty()){
    38. return false;
    39. }
    40. head = head->next;
    41. delete node;
    42. node = nullptr;
    43. curSize--;
    44. return true;
    45. }
    46. int Front() {
    47. if(isEmpty()){
    48. return -1;
    49. }
    50. return head->val;
    51. }
    52. int Rear() {
    53. if(isEmpty()){
    54. return -1;
    55. }
    56. return tail->val;
    57. }
    58. bool isEmpty() {
    59. bool isSucc = false;
    60. if(curSize == 0){
    61. isSucc = true;
    62. }
    63. return isSucc;
    64. }
    65. bool isFull() {
    66. bool isSucc = false;
    67. if(curSize == maxSize){
    68. isSucc = true;
    69. }
    70. return isSucc;
    71. }
    72. private:
    73. int maxSize;
    74. int curSize;
    75. sq* head;
    76. sq* tail;
    77. };
  • 相关阅读:
    超越传统插值:利用深度学习提升视频帧率与清晰度
    查看进程信息(ps、top) + 操作后台进程(jobs、bg、fg)
    原型和原型对象
    JAVA线程池
    【JavaEE】文件操作
    【2023】Redis数据持久化
    在Postgresql中进行关键字查找
    经验分享,两个在线图片处理网站在线抠图和删除不需要的元素
    Ansys Lumerical | 用于增强现实系统的表面浮雕光栅
    u盘刻录系统安装盘
  • 原文地址:https://blog.csdn.net/qq_16542775/article/details/126178798