FIFO队列

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

题目:设计循环队列

  1. class MyCircularQueue {
  2. private:
  3. vector<int> data;
  4. int head;
  5. int tail;
  6. int size;
  7. public:
  8. /** Initialize your data structure here. Set the size of the queue to be k. */
  9. MyCircularQueue(int k) {
  10. data.resize(k);
  11. head = -1;
  12. tail = -1;
  13. size = k;
  14. }
  15. /** Insert an element into the circular queue. Return true if the operation is successful. */
  16. bool enQueue(int value) {
  17. if (isFull()) {
  18. return false;
  19. }
  20. if (isEmpty()) {
  21. head = 0;
  22. }
  23. tail = (tail + 1) % size;
  24. data[tail] = value;
  25. return true;
  26. }
  27. /** Delete an element from the circular queue. Return true if the operation is successful. */
  28. bool deQueue() {
  29. if (isEmpty()) {
  30. return false;
  31. }
  32. if (head == tail) {
  33. head = -1;
  34. tail = -1;
  35. return true;
  36. }
  37. head = (head + 1) % size;
  38. return true;
  39. }
  40. /** Get the front item from the queue. */
  41. int Front() {
  42. if (isEmpty()) {
  43. return -1;
  44. }
  45. return data[head];
  46. }
  47. /** Get the last item from the queue. */
  48. int Rear() {
  49. if (isEmpty()) {
  50. return -1;
  51. }
  52. return data[tail];
  53. }
  54. /** Checks whether the circular queue is empty or not. */
  55. bool isEmpty() {
  56. return head == -1;
  57. }
  58. /** Checks whether the circular queue is full or not. */
  59. bool isFull() {
  60. return ((tail + 1) % size) == head;
  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. */