To understand the implementation of a queue using an array using C++
Objective
To understand the implementation of a queue using an array using C++
#include <iostream>
using namespace std;
#define maxSize 5
int queue[maxSize], front = -1, rear = -1;
void Enqueue(int value) {
if(rear == maxSize - 1) {
cout << "Queue is full" << endl;
} else {
if(front == -1) {
front = 0;
}
rear++;
queue[rear] = value;
cout << "Enqueue: " << value << endl;
}
}
void Dequeue() {
if(front == -1 || front > rear) {
cout << "Queue is empty" << endl;
} else {
cout << "Dequeue: " << queue[front] << endl;
front++;
}
}
int main() {
Enqueue(1);
Enqueue(2);
Enqueue(3);
Enqueue(4);
Enqueue(5);
Dequeue();
Dequeue();
Dequeue();
Dequeue();
Dequeue();
return 0;
}
Discussion of Algorithm
- Start
- Declare and initialize an array with a certain size for the queue
- Declare a front and rear variable, both initially set to -1
- Implement Enqueue operation (insert at rear)
- Implement Dequeue operation (remove from front)
- End
Representations
Flow Diagram
+----------------------------------+ | | | Start | | | | | V | | Enqueue | | | | +----------------------------------+ | V +----------------------------------+ | | | Queue is full | | | | +----------------------------------+ | V +----------------------------------+ | | | Enqueue | | | | +----------------------------------+ | V +----------------------------------+ | | | Enqueue | | | | +----------------------------------+ | V +----------------------------------+ | | | Enqueue | | | | +----------------------------------+ | V +----------------------------------+ | | | Enqueue | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue: 1 | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue: 2 | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue: 3 | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue: 4 | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue | | | | +----------------------------------+ | V +----------------------------------+ | | | Dequeue: 5 | | | | +----------------------------------+ | V +----------------------------------+ | | | Exit | | | | +----------------------------------+
Tabular Dry Run
Enqueue | Dequeue 1 | 2 | 3 | 4 | 5 | | 1 | 2 | 3 | 4 | 5
Results/Output
Enqueue: 1 Enqueue: 2 Enqueue: 3 Enqueue: 4 Enqueue: 5 Dequeue: 1 Dequeue: 2 Dequeue: 3 Dequeue: 4 Dequeue: 5