// implementation file for the queue class
#include <iostream>
using namespace std;
const int queue_size = 6;
class queue
{
private:
char data [queue_size]; // elements in the queue
int front, // index to the front of the queue, indexes one previous
// to actual front element (remove)
rear; // index of the rear element;
public:
queue (); // create an empty queue
void enqueue (char item); // adds an element to the rear
char dequeue (); // removes an element from the front
bool empty (); // returns true for an empty queue
bool full (); // returns true for a full queue
int elements (); // returns the number of elements in the queue
void print (); // prints the queue from front to rear
};
// returns the number of elements in the queue. If queue is empty, it returns 0.
int queue::elements ()
{
int i;
if(empty())
return 0;
else
for (i = front+1; i != (rear + 1) % queue_size; i = (i + 1)%queue_size)
return i;
}
// prints the elements in the queue from first to last element. If the queue is empty, nothing
// is printed
void queue::print ()
{
int i;
if(!empty())
for (i = front+1; i != (rear + 1) % queue_size; i = (i + 1)%queue_size)
cout << data[i] << " ";
}
// constructor creates an empty queue
queue::queue ()
{
front = 0;
rear = 0;
}
// enqueue adds an element to the rear of the queue
void queue::enqueue (char item)
{
// if full, can't add another element
if (full ())
{
cout << "\n\nQueue Error: Can't add to a full queue";
cout << "\nQueue will not be changed";
}
else // ok to add an item
{
rear = (rear + 1) % queue_size;
data [rear] = item;
}
}
// dequeue removes an element from the front of the queue
char queue::dequeue ()
{
// if the queue is empty, we can't remove a value
if (empty ())
{
cout << "\n\nQueue Error: Can't remove from an empty queue";
cout << "\nReturning a blank";
return ' ';
}
else // ok to remove a value
{
front = (front + 1) % queue_size;
return data [front];
}
}
// empty returns true if the queue is empty
bool queue::empty ()
{
return front == rear;
}
// full returns true if the queue is full
bool queue::full ()
{
return (rear + 1) % queue_size == front;
}
int main()
{
queue q;
q.enqueue('a');
q.enqueue('b');
q.enqueue('c');
q.enqueue('d');
q.enqueue('e');
q.print();
}