Sunday, February 28, 2010

Chapter 2: Basic Abstract Data Types. Problem 2.20

Implement a circular queue where --
1. A pointer to the first element is kept.
2. Length of the queue is kept.

//problem 2.20 - circular queue - keep pointer to first element + length.

#include <iostream>
using namespace std;

const int MAXLENGTH = 10;

class CIRQUEUE
{
int list[MAXLENGTH];
int front;
int length;

public:
//Constructor
CIRQUEUE();
bool QEmpty() { return !length; }
bool QFull() { return length == MAXLENGTH ? true : false; }
bool EnQueue(int val);
bool DeQueue(int& val); //OUTPUT = val
void PrintQ();
};

CIRQUEUE::CIRQUEUE()
{
memset(list, 0, sizeof(list));
front = length = 0;
}

bool CIRQUEUE::EnQueue(int val)
{
if( QFull() )
{
cout << "ERROR: Queue is full" << endl;
return false;
}

list[(front+length)%MAXLENGTH] = val;
length++;
return true;
}

bool CIRQUEUE::DeQueue(int& val) //OUTPUT = val
{
if( QEmpty() )
{
cout << "ERROR: Queue is empty" << endl;
return false;
}

val = list[front];
front = (front+1)%MAXLENGTH;
length--;
return true;
}

void CIRQUEUE::PrintQ()
{
if( QEmpty() )
{
cout << "EMPTY CIRQUEUE." << endl;
return;
}

cout << "CIRQUEUE is ---->" << endl;

int curr = front;
for ( int n = 0; n < length; n++ )
{
cout << list[curr] << " ";
curr = (curr+1)%MAXLENGTH;
}
cout << endl << "<---- END of CIRQUEUE" << endl;
}

//Little driver program to test this
void main()
{
CIRQUEUE q;
q.PrintQ();
int val = 0;

cout << endl << "EnQueuing 10 elements.. " << endl;
for( val = 0; q.EnQueue(val); val++)
q.PrintQ();

cout << endl << "DeQueuing 5 elements.. " << endl;
q.DeQueue(val);
q.PrintQ();
q.DeQueue(val);
q.PrintQ();
q.DeQueue(val);
q.PrintQ();
q.DeQueue(val);
q.PrintQ();
q.DeQueue(val);
q.PrintQ();

cout << endl << "EnQueuing 10 elements.. " << endl;
for( val = 0; q.EnQueue(val); val++)
q.PrintQ();
}

No comments:

Post a Comment