Description: A queue is a linear data structure that follows the First In First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed. Think of it like a line of people waiting to buy tickets: the person who arrives first is the one who gets served first.
Queues can be implemented using various data structures, such as:
Here's a C++ implementation of a queue using a linked list:
#include <iostream>
using namespace std;
// Node structure for linked list
struct Node {
int data;
Node* next;
};
// Queue class
class Queue {
private:
Node* front;
Node* rear;
int size;
public:
Queue() : front(nullptr), rear(nullptr), size(0) {}
// Enqueue operation
void enqueue(int value) {
Node* newNode = new Node{value, nullptr};
if (rear) {
rear->next = newNode; // Link the new node at the end of the queue
}
rear = newNode; // Move the rear pointer to the new node
if (!front) {
front = rear; // If the queue was empty, front is also the new node
}
size++;
}
// Dequeue operation
int dequeue() {
if (isEmpty()) {
throw runtime_error("Queue is empty");
}
int value = front->data; // Get the data from the front node
Node* temp = front; // Temporary variable to delete the front node
front = front->next; // Move front pointer to the next node
delete temp; // Delete the old front node
size--;
if (isEmpty()) {
rear = nullptr; // If the queue is empty, update rear as well
}
return value;
}
// Peek at the front element
int peek() {
if (isEmpty()) {
throw runtime_error("Queue is empty");
}
return front->data; // Return the front element's data
}
// Check if the queue is empty
bool isEmpty() {
return size == 0;
}
// Get the size of the queue
int getSize() {
return size;
}
~Queue() {
while (!isEmpty()) {
dequeue(); // Dequeue all elements to free memory
}
}
};
int main() {
Queue q;
// Enqueue elements
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
cout << "Front element: " << q.peek() << endl; // Should print 10
cout << "Dequeued: " << q.dequeue() << endl; // Should remove 10
cout << "New front element: " << q.peek() << endl; // Should print 20
cout << "Size of queue: " << q.getSize() << endl; // Should print 2
return 0;
}
Queues are fundamental data structures used in various applications, such as scheduling tasks, handling requests, and managing resources in computer systems. Their FIFO nature makes them suitable for scenarios where order matters. Understanding how to implement and use queues is essential for effective algorithm design and problem-solving in programming.
Open this section to load past papers