Data Structure & Algorithms
Data Structure & Algorithms
&
ALGORITHMS
QUEUE
BY :- TASLIMBANU MASTAN SHAIKH
TY ENTC
GUIDED BY :- SHANMUKH MAM
•WHAT IS A QUEUE?
• It is an ordered group of homogeneous items of elements.
• Queues have two ends:
• Elements are added at one end.
• Elements are removed from the other end.
• The element added first is also removed first (FIFO: First In,
First Out).
•QUEUE SPECIFICATION
•Definitions: (provided by the user)
•MAX_ITEMS: Max number of items that
might be on the queue
•ItemType: Data type of the items on the
queue
•ENQUEUE (ITEM TYPE NEW ITEM)
•Function: Adds new Item to the rear of the
queue.
•Preconditions: Queue has been initialized
and is not full.
•Postconditions: new Item is at rear of
queue.
•DEQUEUE (ITEM TYPE& ITEM)
•Function: Removes front item from queue
and returns it in item.
•Preconditions: Queue has been initialized
and is not empty.
•Postconditions: Front element has been
removed from queue and item is a copy of
removed element.
•IMPLEMENTATION ISSUES
•Implement the queue as a circular
structure.
•How do we know if a queue is full or
empty?
•Initialization of front and rear.
•Testing for a full or empty queue.
Make front point to the element preceding the front
element in the queue (one memory location will be
wasted).
Initialize front and rear
Queue is empty
now!!
rear == front
QUEUE IMPLEMENTATION
template<class ItemType> private:
class QueueType { int front;
int rear;
public: ItemType* items;
QueueType(int); int maxQue;
};
QueueType();
~QueueType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Enqueue(ItemType);
void Dequeue(ItemType&);
QUEUE IMPLEMENTATION (CONT.)
template<class ItemType>
QueueType<ItemType>::QueueType(int
max)
{
maxQue = max + 1;
front = maxQue - 1;
rear = maxQue - 1;
items = new ItemType[maxQue];
}
Queue Implementation (cont.)
template<class ItemType>
QueueType<ItemType>::~QueueType()
{
delete [] items;
}
Queue Implementation
(cont.)
template<class ItemType>
void QueueType<ItemType>::
MakeEmpty()
{
front = maxQue - 1;
rear = maxQue - 1;
}
QUEUE IMPLEMENTATION (CONT.)
template<class ItemType>
bool QueueType<ItemType>::IsEmpty() const
{
return (rear == front);
}
template<class ItemType>
bool QueueType<ItemType>::IsFull() const
{
return ( (rear + 1) % maxQue == front);
}
Queue Implementation
(cont.)
template<class ItemType>
void QueueType<ItemType>::Enqueue (ItemType
newItem)
{
rear = (rear + 1) % maxQue;
items[rear] = newItem;
}
Queue Implementation
(cont.)
template<class ItemType>
void QueueType<ItemType>::Dequeue
(ItemType& item)
{
front = (front + 1) % maxQue;
item = items[front];
}
•Queue overflow
•The condition resulting from trying to add
an element onto a full queue.
if(!q.IsFull())
q.Enqueue(item);
•Queue underflow
•The condition resulting from trying to
remove an element from an empty queue.
if(!q.IsEmpty())
q.Dequeue(item);