Pr11
Queues are frequently used in computer programming, and a typical example is the creation of a job
queue by an operating system. If the operating system does not use priorities, then the jobs are
processed in the order they enter the system. Write C++ program for simulating job queue. Write
functions to add job and delete job from queue
Objectives:-
1. To understand concept of queue.
2. To study the different types of queues.
3. To study the job scheduling problem as queue application.
#include <iostream>
#include <string>
using namespace std;
// Define a structure for a job node
struct JobNode {
string jobID; // Job identifier (could be a string or any type of ID)
JobNode* next; // Pointer to the next job node
JobNode(string id) : jobID(id), next(nullptr) {}
};
// Class to represent a job queue
class JobQueue {
private:
JobNode* front; // Front pointer of the queue
JobNode* rear; // Rear pointer of the queue
public:
// Constructor to initialize the queue
JobQueue() : front(nullptr), rear(nullptr) {}
// Function to add a job to the queue
void addJob(const string& jobID) {
JobNode* newJob = new JobNode(jobID);
if (rear == nullptr) {
front = rear = newJob; // If the queue is empty, front and rear will point to the new job
} else {
rear->next = newJob; // Add the new job at the end of the queue
rear = newJob; // Update the rear pointer
}
cout << "Job " << jobID << " added to the queue." << endl;
}
// Function to delete a job from the queue
void deleteJob() {
if (front == nullptr) {
cout << "Queue is empty! No jobs to delete." << endl;
return;
}
JobNode* temp = front;
front = front->next; // Move the front pointer to the next job
cout << "Job " << temp->jobID << " deleted from the queue." << endl;
delete temp; // Free the memory of the deleted job
if (front == nullptr) {
rear = nullptr; // If the queue is empty, update the rear pointer to nullptr
}
}
// Function to display the jobs in the queue
void displayQueue() {
if (front == nullptr) {
cout << "Queue is empty!" << endl;
return;
}
JobNode* temp = front;
cout << "Jobs in the queue: ";
while (temp != nullptr) {
cout << temp->jobID << " ";
temp = temp->next;
}
cout << endl;
}
// Destructor to free memory used by the queue
~JobQueue() {
while (front != nullptr) {
JobNode* temp = front;
front = front->next;
delete temp;
}
}
};
int main() {
JobQueue queue;
// Adding jobs to the queue
queue.addJob("Job1");
queue.addJob("Job2");
queue.addJob("Job3");
// Display the jobs in the queue
queue.displayQueue();
// Deleting a job from the queue
queue.deleteJob();
// Display the jobs after deletion
queue.displayQueue();
// Deleting another job from the queue
queue.deleteJob();
// Display the jobs after another deletion
queue.displayQueue();
return 0;
}
Comments
Post a Comment