CmSc 250 Intro to Algorithms
QUEUES
Definition: A sequence of elements of the same type.
The first stored
element is first accessible.
The structure is known also under the name FIFO - first in first out.
Basic operations:
Put (EnQueue): store a data item at the end of the queue
Get (DeQueue): retrieve a data item from the beginning of the queue
Notation:
Q - queue
e - item of same type as the elements of Q
b - boolean value
Operations:
InitQueue(Q)
QueueEmpty(Q) à b
QueueFull(Q) à b
Put(Q,e)
Get(Q)à e
Problem 1:
AppendQueue(Q,P): A procedure to append a queue P onto the end of a queue Q, leaving P empty.
Pre: queue P and queue Q
initialized (possibly empty)
Post: Q contains all elements originally in Q followed by the elements
that were in P in same order. P is empty.
Algorithm:
While not QueueEmpty(P) do
The same problem can be solved using recursive function calls instead of a loop:
AppendQueue(Q,P)
{
If not QueueEmpty(P) then
The "loop" version of the algorithm is the preferred one as it is simpler,
and the recursion is nothing more than a hidden loop.
Complexity of the algorithm: O(N), N - the number of elements in P.
Problem 2: (Solution)
ReverseQueue(Q): A procedure to reverse the elements in a queue Q
Pre:
Problem 3: (Solution)
AppendReverseQueue(Q,P): A procedure to append a queue P in reverse
order
onto the end of a queue Q, leaving P empty.
Pre: queue P and queue Q initialized (possibly empty)
Post: Q contains all elements originally in Q followed by the elements
that were in P in reverse order.
P is empty