Queue
Queue
A queue is a linear data structure that follows the First In First Out (FIFO) principle.
Implementation
// Queue implementation in C++
#include <iostream>
#define SIZE 5
using namespace std;
class Queue {
private:
int items[SIZE], front, rear;
public:
() {
Queue= -1;
front = -1;
rear }
bool isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}
bool isEmpty() {
if (front == -1)
return true;
else
return false;
}
void enQueue(int element) {
if (isFull()) {
<< "Queue is full";
cout } else {
if (front == -1) front = 0;
++;
rear[rear] = element;
items<< endl
cout << "Inserted " << element << endl;
}
}
int deQueue() {
int element;
if (isEmpty()) {
<< "Queue is empty" << endl;
cout return (-1);
} else {
= items[front];
element if (front >= rear) {
= -1;
front = -1;
rear } /* Q has only one element, so we reset the queue after deleting it. */
else {
++;
front}
<< endl
cout << "Deleted -> " << element << endl;
return (element);
}
}
void display() {
/* Function to display elements of Queue */
int i;
if (isEmpty()) {
<< endl
cout << "Empty Queue" << endl;
} else {
<< endl
cout << "Front index-> " << front;
<< endl
cout << "Items -> ";
for (i = front; i <= rear; i++)
<< items[i] << " ";
cout << endl
cout << "Rear index-> " << rear << endl;
}
}
};
int main() {
;
Queue q
//deQueue is not possible on empty queue
.deQueue();
q
//enQueue 5 elements
.enQueue(1);
q.enQueue(2);
q.enQueue(3);
q.enQueue(4);
q.enQueue(5);
q
// 6th element can't be added to because the queue is full
.enQueue(6);
q
.display();
q
//deQueue removes element entered first i.e. 1
.deQueue();
q
//Now we have just 4 elements
.display();
q
return 0;
}
Explanation
front
andrear
are the indices of the front and rear elements of the queue.isFull
checks if the queue is full.isEmpty
checks if the queue is empty.enQueue
adds an element to the queue.deQueue
removes an element from the queue.display
displays the elements of the queue.
Time Complexity
enQueue
anddeQueue
are O(1) operations.display
is O(n) operation.