We can now address three more procedures: how to insert a fan into a queue, how to remove a fan from the queue, and how to print the queue. Let us take the printing procedure first. Here it is:
PROC print queue = (REF REF QUEUE head)VOID:
IF head IS nilq
THEN print(("NIL",newline))
ELSE print((newline,
"(",name OF fan OF head,",",
whole(ticket OF fan OF head,0),
")=>"));
print queue(next OF head)
FI
By not using the triple REF name for the head of the
queue, we can use recursion to simplify the
procedure. Recursion is common in procedures for
linked-lists.
Inserting a fan is a little more difficult. There are several
possibilities: the queue can be empty or non-empty. If it is
non-empty, the fan can be inserted at the head of the queue, or if
there are at least two fans in the queue, the fan could be inserted
somewhere between the head and the tail. The question is, how many
parameters are required for the procedure? Clearly, we need
head to determine whether the queue is empty,
tail to be updated in case it is or if the fan is to be
added to the end of the queue. Here is a possible header:
PROC insert fan=(REF REF REF QUEUE head,tail,
REF FAN fan)VOID:
We need a criterion for determining where in the queue a fan should
be inserted. Here is one: the fans should be inserted in the order of
ticket number (using a queue is not an efficient way of doing this,
but this criterion will do for our purposes). Here is insert
fan with a diagram to help you understand it:
PROC insert fan=(REF REF REF QUEUE head,tail,
REF FAN fan)VOID:
IF head IS nilq
THEN #the queue is empty#
REF REF QUEUE(head):=
HEAP QUEUE:=(fan,nilq);
tail:=next OF head
ELIF ticket OF fan < ticket OF fan OF head
THEN
#insert the fan at the head of the queue#
REF REF QUEUE(head):=
HEAP QUEUE:=(fan,head)
ELIF next OF head IS nilq
THEN #add the fan after the head#
REF REF QUEUE(tail):=
HEAP QUEUE:=(fan,nilq);
tail:=next OF tail
ELIF REF QUEUE marker:=head;
WHILE
IF (next OF marker ISNT nilq)
THEN
ticket OF fan
>
ticket OF fan OF next OF marker
ELSE FALSE
FI
DO marker:=next OF marker OD;
next OF marker IS nilq
THEN
#add the fan to the end of the queue#
REF REF QUEUE(tail):=
HEAP QUEUE:=(fan,nilq);
tail:=next OF tail
ELSE
CO insert the fan between `marker'
and `next of marker' CO
next OF marker:=
HEAP QUEUE:=(fan,next OF marker)
FI
There are three lines where you need to look carefully at the modes and values involved:
(fan,head),
(fan,next OF marker),
> operator.
Discussion of this procedure completes our examination of queues.
insert fan, explain the circumstances
in which the loop will terminate. Ans
print queue, confirm that the
procedure insert fan works. Ans
delete fan which will delete a fan
with a given ticket number from the queue. It should yield the fan if
it has been deleted and FALSE if it cannot be found. This
diagram should help you:
Sian Mountbatten 2012-01-19