Queue Operations
In the previous screen, we learned about the basics of queues and how to implement a queue using an array. Now let's explore the fundamental operations that we can perform on a queue.
The main operations that we can perform on a queue are:
enqueue()
: Adds an element to the rear of the queue.dequeue()
: Removes the front element from the queue and returns it.peek()
: Returns the front element of the queue without removing it.
Let's take a look at the C++ implementation of these operations:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4class Queue {
5private:
6 int front;
7 int rear;
8 int capacity;
9 int* queue;
10
11public:
12 Queue(int size) {
13 capacity = size;
14 front = 0;
15 rear = -1;
16 queue = new int[capacity];
17 }
18
19 void enqueue(int element) {
20 // Check if the queue is full
21 if (rear == capacity - 1) {
22 cout << "Queue is full!" << endl;
23 return;
24 }
25
26 // Add element to the rear
27 queue[++rear] = element;
28 cout << "Enqueued: " << element << endl;
29 }
30
31 int dequeue() {
32 // Check if the queue is empty
33 if (front > rear) {
34 cout << "Queue is empty!" << endl;
35 return -1;
36 }
37
38 // Remove and return the front element
39 int element = queue[front++];
40 cout << "Dequeued: " << element << endl;
41 return element;
42 }
43
44 int peek() {
45 // Check if the queue is empty
46 if (front > rear) {
47 cout << "Queue is empty!" << endl;
48 return -1;
49 }
50
51 // Return the front element
52 return queue[front];
53 }
54};
55
56int main() {
57 Queue queue(5);
58 queue.enqueue(10);
59 queue.enqueue(20);
60 queue.enqueue(30);
61 queue.enqueue(40);
62 queue.enqueue(50);
63 queue.enqueue(60); // Queue is full!
64
65 queue.dequeue();
66 queue.dequeue();
67 queue.dequeue();
68 queue.dequeue();
69 queue.dequeue();
70 queue.dequeue(); // Queue is empty!
71
72 return 0;
73}
xxxxxxxxxx
28
using namespace std;
// Queue implementation using an array
class Queue {
private:
int front; // front pointer
int rear; // rear pointer
int capacity; // capacity of the queue
int* queue; // dynamic array to store the elements
public:
Queue(int size) {
capacity = size;
front = 0;
rear = -1;
queue = new int[capacity];
}
// Other member functions
// ...
};
int main() {
// replace with your c++ logic here
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment