fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Queue {
  5. public:
  6. int front, rear, size;
  7. unsigned cap;
  8. int* arr;
  9. };
  10.  
  11. Queue* createQueue(int cap)
  12. {
  13. Queue* queue = new Queue();
  14. queue->cap = cap;
  15. queue->front = queue->size = 0;
  16.  
  17. queue->rear = cap - 1;
  18. queue->arr = new int[(queue->cap * sizeof(int))];
  19. return queue;
  20. }
  21.  
  22. int isFull(Queue* queue)
  23. {
  24. return (queue->size == queue->cap);
  25. }
  26.  
  27. int isempty(Queue* queue) { return (queue->size == 0); }
  28.  
  29.  
  30. void enqueue(Queue* queue, int item)
  31. {
  32. if (isFull(queue))
  33. return;
  34. queue->rear = (queue->rear + 1) % queue->cap;
  35. queue->arr[queue->rear] = item;
  36. queue->size = queue->size + 1;
  37. cout << item << " enqueued to queue\n";
  38. }
  39.  
  40. int dequeue(Queue* queue)
  41. {
  42. if (isempty(queue))
  43. return INT_MIN;
  44. int item = queue->arr[queue->front];
  45. queue->front = (queue->front + 1) % queue->cap;
  46. queue->size = queue->size - 1;
  47. return item;
  48. }
  49. int front(Queue* queue)
  50. {
  51. if (isempty(queue))
  52. return INT_MIN;
  53. return queue->arr[queue->front];
  54. }
  55. int rear(Queue* queue)
  56. {
  57. if (isempty(queue))
  58. return INT_MIN;
  59. return queue->arr[queue->rear];
  60. }
  61.  
  62.  
  63. int main()
  64. {
  65. Queue* queue = createQueue(1000);
  66. enqueue(queue, 10);
  67. enqueue(queue, 20);
  68. enqueue(queue, 30);
  69. enqueue(queue, 40);
  70. cout << dequeue(queue);
  71. cout << " dequeued from queue\n";
  72. cout << "Front item is " << front(queue) << endl;
  73. cout << "Rear item is " << rear(queue);
  74. return 0;
  75. }
  76.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
40 enqueued to queue
10 dequeued from queue
Front item is 20
Rear item is 40