Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Topic 04 Queues

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Data Structures

Afsah Imtiaz Elahi, Data Structures 18


class Queue {
public:
Queue(int s = 10); // constructor - default size = 10
~Queue() {delete [ ] QueueArray; } // destructor
bool add (int);
bool remove (int &);
bool isFull() {return size == MaxSize;}
bool isEmpty() {return size == 0; }
private:
int maxSize; // max Queue size
int front, rear;
int *QueueArray;
int size; // no. of elements in the Queue
};
bool Queue::add(int n)
{
if (! isFull() ) {
QueueArray[rear] = n;
rear++;
if (rear == maxSize) 3
rear = 0;
size++; 2
return true;
} 1
else return false; MS-1 0
}
bool Queue::remove(int &n)
{
if (! isEmpty() {
n = QueueArray[front];
front++;
3 if (front == maxSize)
front = 0;
2 size--;
return true;
1
MS-1 0 }
else return false;
}
Queue::Queue(int s)
{
if (s <= 0) MaxSize = 10; else MaxSize = s;
QueueArray = new int[MaxSize];
size = 0; rear = 0; front = 0; 3

} 2
bool Queue::isFull() {return size == MaxSize;} 1
bool Queue::isEmpty() {return size == 0; }
MS-1 0
bool Queue::add(int n) bool Queue::remove(int &n)
{ {
if (! isFull() ) { if (! isEmpty() ) {
QueueArray[rear] = n; n = QueueArray[rear];
rear++; front++;
if (rear == maxSize) if (front == maxSize)
rear = 0; front = 0;
size++; size--;
return true; return true;
} }
else return false; else return false;
} }
Add: rear = (rear + 1) % maxSize;

Remove: front = (front + 1) % maxSize;


3

1
MS-1 0
bool Queue::add(int n) bool Queue::remove(int &n)
{ {
if (! isFull() ) { if (! isEmpty() {
QueueArray[rear] = n; n = QueueArray[front];
rear++; front++;
if (rear == maxSize) if (front == maxSize)
rear = 0; front = 0;
size++; size--;
return true; return true;
} }
else return false; else return false;
} }
isEmpty: rear == front

isFull: rear == (front + 1) % MaxSize


3

2
isEmpty: size == 0
1
isFull: size == maxSize MS-1 0
bool Queue::add(int n) bool Queue::remove(int &n)
{ {
if (! isFull() ) { if (! isEmpty() {
QueueArray[rear] = n; n = QueueArray[front];
rear++; front++;
if (rear == maxSize) if (front == maxSize)
rear = 0; front = 0;
size++; size--;
return true; return true;
} }
else return false; else return false;
} }
Afsah Imtiaz Elahi, Data Structures 25
 Introduction to Data Structures and Algorithm
Analysis With C++, by D. Samanta

 Data Structures and Algorithm Analysis in


C++ by Mark Allen Weiss

Afsah Imtiaz Elahi, Data Structures 29

You might also like