06 Queues
06 Queues
NOW!
Initialize front and rear
Queue Implementation (cont.)
template<class ItemType>
QueueType<ItemType>::QueueType(int max)
{
maxQue = max + 1;
front = maxQue - 1; O(1)
rear = maxQue - 1;
items = new ItemType[maxQue];
}
Queue Implementation (cont.)
template<class ItemType>
QueueType<ItemType>::~QueueType()
{
delete [] items; O(1)
}
Queue Implementation (cont.)
template<class ItemType>
void QueueType<ItemType>::MakeEmpty()
{
front = maxQue - 1; O(1)
rear = maxQue - 1;
}
Queue Implementation (cont.)
template<class ItemType>
bool QueueType<ItemType>::IsEmpty() const
{
return (rear == front);
} O(1)
template<class ItemType>
bool QueueType<ItemType>::IsFull() const
{
return ( (rear + 1) % maxQue == front);
}
O(1)
Enqueue (ItemType newItem)
• Function: Adds newItem to the rear of the
queue.
• Preconditions: Queue has been initialized
and is not full.
• Postconditions: newItem is at rear of queue.
Queue Implementation (cont.)
template<class ItemType>
void QueueType<ItemType>::Enqueue
(ItemType newItem)
{
rear = (rear + 1) % maxQue;
items[rear] = newItem; O(1)
}
Dequeue (ItemType& 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.
Queue Implementation (cont.)
template<class ItemType>
void QueueType<ItemType>::Dequeue
(ItemType& item)
{
front = (front + 1) % maxQue;
O(1)
item = items[front];
}
Queue overflow
(1) Read the line of text into both a stack and a queue.
s.Pop(sItem);
q.Dequeue(qItem);
if(sItem != qItem)
++mismatches;
}
if (mismatches == 0)
cout << "That is a palindrome" << endl;
else
cout << "That is not a palindrome" << endl;
return 0;
}
Exercise 37 (page 337): Implement a client
function that returns the number of items in a
queue. The queue is unchanged.