home *** CD-ROM | disk | FTP | other *** search
- UNIT queues;
- (* Turbo Pascal 5.5 program *)
-
- (**********************)
- (**) INTERFACE (**)
- (**********************)
- TYPE
- GenericItem = OBJECT {This object is nothing}
- DESTRUCTOR done; virtual; {by itself, but you can}
- END; {make ANY other object }
- {a descendant of it. }
-
- ItemPtr = ^GenericItem;
- ItemList = ^ItemNode;
- ItemNode = RECORD
- item : ItemPtr;
- next : ItemList;
- END;
-
- queue = OBJECT (GenericItem)
- front, rear : ItemList;
- length, maxlength : Word;
- CONSTRUCTOR Init;
- PROCEDURE MakeNull;
- PROCEDURE enqueue(I : ItemPtr);
- FUNCTION dequeue : ItemPtr;
- FUNCTION empty : boolean;
- FUNCTION GetLength : Word;
- FUNCTION GetMax : Word;
- DESTRUCTOR done; virtual;
- END;
-
- (**********************)
- (**) IMPLEMENTATION (**)
- (**********************)
-
- DESTRUCTOR GenericItem.done; BEGIN END;
-
- CONSTRUCTOR queue.Init;
- { To initialize a queue, create a "front" pointer
- for it and set the "rear" pointer to the same
- as the front. Note that the actual queue of
- items starts at "front^.next" -- "front" is
- just a header node }
- BEGIN
- New(front);
- front^.next := NIL;
- Front^.item := NIL;
- rear := front;
- length := 0;
- maxlength := 0;
- END;
-
- PROCEDURE queue.MakeNull;
- { To empty a queue, dispose of nodes until
- the front of the line equals the rear }
- VAR P : ItemList;
- BEGIN
- WHILE front <> rear DO
- BEGIN
- P := front;
- front := front^.next;
- IF P^.item <> NIL THEN
- dispose(P^.item, done);
- dispose(P);
- END;
- END;
-
- PROCEDURE queue.enqueue(I : ItemPtr);
- { To enqueue an item, add it to the rear of the queue }
- BEGIN
- Inc(length);
- IF length > maxlength THEN maxlength := length;
- New(rear^.next);
- rear := rear^.next;
- rear^.item := I;
- rear^.next := NIL;
- END;
-
- FUNCTION queue.dequeue : ItemPtr;
- { To dequeue an item, return the contents of the
- frontmost node (the one after the "front" header),
- advance the front pointer, and dispose of the
- previous front }
- VAR P : ItemList;
- BEGIN
- IF empty THEN dequeue := NIL
- ELSE
- BEGIN
- dequeue := front^.next^.item;
- P := front;
- front := front^.next;
- front^.item := NIL;
- dispose(P);
- Dec(length);
- END;
- END;
-
- FUNCTION queue.empty : boolean;
- BEGIN empty := front = rear; END;
-
- FUNCTION queue.GetLength : Word;
- BEGIN GetLength := length; END;
-
- FUNCTION queue.Getmax : Word;
- BEGIN Getmax := maxlength; END;
-
- DESTRUCTOR queue.done;
- { This procedure calls MakeNull to dispose
- all of the nodes except "front", then
- gets rid of "front" as well }
- BEGIN
- MakeNull;
- dispose(front);
- END;
-
- END.