Вы находитесь на странице: 1из 47

Based on the lecture notes of F.M.Carrano and J.J.

Prichard

ADT queue: Applications and Implementations


COMPSCI 105 C S1 Recommended reading: Chapter 8 of the textbook

What is a Queue?

Can you think of other examples of queues?


2 COMPSCI 105 ADT Queue

The Abstract Data Type Queue


!!

Queues are appropriate for many real-world situations


!! !!

Example: A line to buy a movie ticket Computer applications, e.g. a request to print a document
!!

Simulation to see how to reduce the wait involved in an application

!!

A queue
!! !! !!

New items enter at the back, or rear, of the queue Items leave from the front of the queue First-in, first-out (FIFO) property:
!!

The first item inserted into a queue is the first item to leave

COMPSCI 105

ADT Queue

The Abstract Data Type Queue


!!

ADT queue operations (with their pseudocodes)


!!

Create an empty queue:


createQueue()

!!

Determine whether a queue is empty:


isEmpty()

!!

Add a new item to the queue:


enqueue( newItem ) throws QueueException // Adds newItem at the back of a queue. Throws
// QueueException if the operation is unsuccessful

COMPSCI 105

ADT Queue

The Abstract Data Type Queue


!!

ADT queue operations (with their pseudocodes)


!!

Remove from the queue the item that was added earliest:
dequeue() throws QueueException // Retrieves and removes the front of a queue. // Throws QueueException if the operation is // unsuccessful

!!

Remove all the items from the queue:


dequeueAll()

!!

Retrieve from the queue the item that was added earliest:
peek() throws QueueException // Retrieves the front of a queue. Throws // QueueException if the retrieval is unsuccessful

COMPSCI 105

ADT Queue

More formally
Queues implement the FIFO (first-in first-out) policy: e.g. the printer / job queue!
dequeue() enqueue( o )

dequeueAll()

isEmpty() peek()
6 COMPSCI 105

createQueue()
ADT Queue

Queue ADT Interface


An abstract mechanism to support simultaneous implementations:
public interface QueueInterface { public boolean isEmpty(); // Determines whether a queue is empty public void enqueue( Object newItem ) throws QueueException; // Adds an item at the back of a queue public Object dequeue() throws QueueException; // Retrieves and removes the front of a queue public void dequeueAll(); // Removes all items of a queue public Object peek() throws QueueException; // Retrieves the item at the front of a queue
COMPSCI 105 ADT Queue

}
7

Sample Code
QueueInterface q = new Queue(); q.enqueue (a); q.enqueue (b); q.enqueue (c); d = q.peek(); q.dequeue(); q.enqueue(e); q.dequeue();
8 COMPSCI 105 ADT Queue

q front d back

a b c e

The Abstract Data Type Queue


Fig. 8-2

COMPSCI 105

ADT Queue

Applications
!! !!

Print queue Reading a string of characters


!!

A queue can retain characters in the order in which they are typed queue.createQueue() while ( not end of line ) { read a new character ch queue.enqueue( ch ) }

!!

Once the characters are in a queue, the system can process them as necessary

!! !!

Level order traversal of trees Checking palindrome: e.g. Mac spots tip at a pit-stop scam
!!

To enjoy palindromes, see http://thinks.com/words/palindromes


COMPSCI 105 ADT Queue

10

Convert digits into decimal integer


!!

Reading a sequence of digits separated by space into a queue while(ch is not blank and ch is a digit) { queue.enqueue( ch ) }

!!

Convert digits in queue into a decimal integer n n = 0; while ( !queue.isEmpty() ) { ch = queue.dequeue(); n = 10 * n + integer that ch represents }
COMPSCI 105 ADT Queue

11

Convert digits into decimal integer


!! !!

An example: a sequence 61835 read into the queue:


!!

53816 n=0 n = 0 * 10 + 6 = 6 n = 6 * 10 + 1 = 61 n = 61 * 10 + 8 = 618 n = 618 * 10 + 3 = 6183 n = 6183 * 10 + 5 = 61835 Terminate and return n: queue is empty
COMPSCI 105 ADT Queue

Conversion:
!! !! !! !! !! !! !!

12

Recognizing Palindrome
!!

A string which reads the same either left to right, or right to left is known as a palindrome
!! !!

Palindromes : r a d a r and d e e d Counter Example : d a t a

! Procedure for a given string:


! Stack to reverse the character order of string ! Queue to preserve the character order of string ! Check if the two sequences are the same

13

COMPSCI 105

ADT Queue

Palindrome Recogniser (Pseudocode)


public static boolean palindrome ( String str ) throws Exception { StackInterface s = new Stack(); QueueInterface q = new Queue(); // push string into stack, and also queue for ( int j = 0; j < str.length(); j++ ) { Character c = new Character( str.charAt( j ) ); s.push( c ); q.enqueue( c ); } // compare the characters in queue with the stack boolean charactersAreEqual = true; while ( !q.isEmpty() && charactersAreEqual ) { Character stackTop = (Character) s.pop(); Character queueFront = (Character) q.dequeue(); if ( stackTop.compareTo( queueFront ) != 0 ) { charactersAreEqual = false; } } // end while return charactersAreEqual; }
14 COMPSCI 105 ADT Queue

Implementations of Queues
Either an array-based or a reference-based implementation Reference-based implementation:
(a) Linear linked list with two external references to the front and to the back (b) Circular linked list with one external reference to the back

Fig. 8-4
15 COMPSCI 105 ADT Queue

Reference-Based Implementation
Inserting an item into a non-empty queue
1.! 2.! 3.!

Change the next reference in the new node to the front of the queue Change the next reference in the back node to the new node Change the external reference lastNode to the new node

Fig. 8-5

lastNode newNode (references new node)

16

COMPSCI 105

ADT Queue

Reference-Based Implementation
!!

Inserting an item into an empty queue


!! !!

Change the next reference in the new node to itself Change the external reference lastNode to the new node (a) before insertion; (b) after insertion

Fig. 8-6:

17

COMPSCI 105

ADT Queue

Deleting an item from a queue of more than one item

Reference-Based Implementation
public class QueueReferenceBased implements QueueInterface { private Node lastNode; public QueueReferenceBased() { lastNode = null }; public Object dequeue() throws QueueException { if ( !isEmpty() ) { Node firstNode = lastNode.getNext(); if ( firstNode == lastNode ) { lastNode = null; } else { lastNode.setNext( firstNode.getNext() ); } return firstNode.getItem(); } else { throw new QueueException ( Queue exception on dequeue: queue empty); } } // end dequeue }
18 COMPSCI 105 ADT Queue

Deleting an item from a queue of more than one item

Reference-Based Implementation
public Object dequeue() throws QueueException { if ( !isEmpty() ) { Node firstNode = lastNode.getNext(); if ( firstNode == lastNode ) { lastNode = null; } else { lastNode.setNext( firstNode.getNext() ); } return firstNode.getItem(); } else { throw new QueueException ( Queue exception on dequeue: queue empty); } } // end dequeue Fig. 8-7

19

COMPSCI 105

ADT Queue

Array-Based Implementation
An array with front and back pointers as implementation of queue
(a) Naive array-based implementation (b) Rightward drift can cause the queue to appear full

(a)

(b) Fig. 8-8

20

COMPSCI 105

ADT Queue

Array-Based Implementation
Solution 1: Shifting array elements to the left after each deletion too expensive !
items

0
front

3
back

2
0

4
1

1
2

7
3 MAX_QUEUE - 1

Solution 2: Viewing the array as a circular structure

(eliminates the problem of rightward drift)

Fig. 8-9
21 COMPSCI 105 ADT Queue

Array-Based Implementation
!! !! !!

A count of the queue items to detect queue-full and queue-empty conditions To initialize the queue, set front to 0, back to MAX_QUEUE 1, and count to 0 Inserting into a queue: back = ( back + 1 ) % MAX_QUEUE;
items[back] = newItem; ++count;

!!

Deleting from a queue: front = ( front + 1 ) % MAX_QUEUE;


--count;

!!

Variations of the array-based implementation:


!! !!

Use a flag full to distinguish between the full and empty conditions Declare MAX_QUEUE + 1 locations for the array items, but use only MAX_QUEUE of them for queue items
COMPSCI 105 ADT Queue

22

How To Advance
!! !!

Queue-empty: front is one slot ahead of back When either front or back advances past MAX_QUEUE - 1, it wraps around to 0
!!

The wrap-around effect: by using modulo arithmetic (the Java % operator)

!!

Counting queue items to detect queue-full and queue-empty conditions

e.g., insert newItem into the queue as: back = ( back+1 ) % MAX_QUEUE; items[back] = newItem; ++count;
Fig. 8-9
23 COMPSCI 105 ADT Queue

Array-Based Implementation
public class QueueArrayBased implements QueueInterface { private final int MAX_QUEUE = 50; private Object [] items; private int front, back, count; // default constructor public QueueArrayBased() { items = new Object[ MAX_QUEUE ]; front = 0; back = MAX_QUEUE - 1; count = 0; }
24 COMPSCI 105 ADT Queue

Array-Based Implementation
public boolean isEmpty() { return count == 0; } public boolean isFull() { return count == MAX_QUEUE; } public void enqueue( Object newItem ) throws QueueException { if ( !isFull() ) { back = ( back + 1 ) % MAX_QUEUE ; items[ back ] = newItem ; ++count ; } else { throw QueueException( "Queue Exception on enqueue: Queue full") ; } } // end enqueue
25 COMPSCI 105 ADT Queue

Array-Based Implementation
public Object dequeue() throws QueueException { if ( !isEmpty() ) { Object queueFront = items[ front ]; front = ( front + 1 ) % MAX_QUEUE ; --count ; return queueFront; } else { throw QueueException( "Queue Exception on dequeue: Queue empty ) ; } } // end dequeue

Fig. 8-10
26 COMPSCI 105 ADT Queue

Array-Based Implementation
!!

front and back cannot be used to distinguish between queuefull and queue-empty conditions for a circular array

Fig. 8-11: (a)


27

front passes back when the queue becomes empty


COMPSCI 105 ADT Queue

Array-Based Implementation

Fig. 8-11: (b)


28

back catches up to front when the queue becomes full


COMPSCI 105 ADT Queue

Array-Based Implementation
Declare MAX_QUEUE + 1 locations for the array items, but use only MAX_QUEUE of them for queue items

a) a full queue;
29

Fig. 8-12:

A more efficient circular implementation: b) an empty queue


COMPSCI 105 ADT Queue

Implementation that Uses ADT List


! ADT List can be used to represent the items in a queue
! dequeue() as list.remove(1) ! peek() as list.get(1) ! enqueue(newItem) as list.add(list.size()+1, newItem)

Fig.8-13
30 COMPSCI 105 ADT Queue

ADT List Implementation


public class QueueListBased implements QueueInterface { private ListReferenceBased list; // default constructor public QueueListBased() { list = new ListReferenceBased(); } public void enqueue( Object newItem ) { list.add( list.size() + 1, newItem ); } // end enqueue
31 COMPSCI 105 ADT Queue

ADT List Implementation


public Object dequeue() throws QueueException { if ( !isEmpty() ) { // queue is not empty; remove front Object queueFront = list.get(1); list.remove(1); return queueFront; } else { throw new QueueException(
"Queue exception on dequeue: queue empty" );

} } // end dequeue } // end class QueueListBased


32

COMPSCI 105

ADT Queue

Comparing Implementations
All implementations are ultimately either array-based or reference-based !! Fixed size versus dynamic size
!!
!! !!

A statically allocated array prevents the enqueue operation from adding an item to the queue if the array is full A resizable array or a reference-based implementation does not impose this restriction on the enqueue operation

A reference-based linked list implementation is more efficient !! The ADT list implementation is simpler to write
!!
33 COMPSCI 105 ADT Queue

Position-oriented ADTs
!!

Three data structures Linked List, Stack, Queue


!!

All of their operations are defined in terms of the positions of their data items Only their end positions can be accessed: FIFO or LIFO !! createStack and createQueue !! stack isEmpty and queue isEmpty !! push and enqueue !! pop and dequeue !! stack peek and queue peek

!!

Stack and Queue are very similar


!!

!!

Linked List allows to insert into, delete from and inspect at any positions of the list
!!

ADT list operations generalise stack and queue operations: !! length !! add, remove, get
COMPSCI 105 ADT Queue

34

The JCF Interface Queue


!!

Java Collection Framework has a queue interface called Queue


!!

Like the List interface, Queue is derived from the interface Collection public interface Queue<E> extends Collection<E> { E element() throws NoSuchElementException;
// Retrieves, but does not remove head; if this queue is empty throws exception

boolean offer( E o ); // Inserts the specified element into this queue, if possible E peek(); // Retrieves, but does not remove head; returns null if this queue is empty E poll(); // Retrieves and removes head, or null if this queue is empty E remove() throws NoSuchElementException; // Retrieves and removes head; if this queue is empty throws exception } // end Queue
35 COMPSCI 105 ADT Queue

Application: Simulation
!! !!

Simulation: a technique for modelling the behaviour of both natural and human-made systems Goal
!!

Generate statistics summarising the performance of an existing system Predict the performance of a proposed system Reduce number of complaints from its customers about how long they have to wait for service from banks tellers Before hiring one more teller: evaluate the approximate average time that a customer has to wait To spend a few days and measure with a stopwatch: not an exciting prospect
COMPSCI 105 ADT Queue

!!

!!

An example: Behaviour of a bank how to optimise?


!!

!!

!!

36

Application: Simulation
!!

More appealing: Computer simulation of the behavior of a bank


!!

!!

First step: a math model that captures the relevant information about the system !! How many tellers does the bank employ? !! How often do customers arrive? Central to a simulation is the notion of simulated time:

Fig.8-14: A
37

simulated blank line at time 0, 12, 20, 38,


COMPSCI 105 ADT Queue

Application: Simulation
!!

If the model accurately describes the real-world system, a simulation can accurately predict the systems performance
!! !!

Predict the average time a customer has to wait before receiving service Evaluate proposed changes to the real-world system
!!

Predict the effect of hiring more tellers in the bank: whether a decrease in the average waiting time for a customer justifies the cost of additional tellers

!!

To gather the information one needs for decision, the simulation of lines of customers runs for a certain specified period of time
!!

In the example on Slide 37:


!! !! !!

Customer 1 waits 0 minutes to begin a transaction, Customer 2 had to wait 18 minutes to begin a transaction An average wait of 9 minutes
COMPSCI 105 ADT Queue

38

Application: Simulation
!!

How to determine when certain events occur?


!!

By studying the real world, mathematicians have learned to model events such as the arrival of people using techniques from probability theory This statistical information is incorporated into the math model of the system and is used to generate events reflecting the real world Uses the events generated by a mathematical model Simulated time is advanced to the time of the next event, e.g. 20 5 -- the 1st customer arrives 20 min into simulation; his service takes 5 min 22 4 -- the 2nd customer arrives 22 min; his service takes 4 min 23 2 -- etc 30 3
COMPSCI 105 ADT Queue

!!

!!

An event-driven simulation:
!! !! !! !! !! !!

39

Application: Simulation
Time Event 20 22 23 25 29 30 31 34
40

Customer 1 enters bank and begins transaction Customer 2 enters bank and stands at end of line Customer 3 enters bank and stands at end of line Customer 1 departs; customer 2 begins transaction Customer 2 departs; customer 3 begins transaction Customer 4 enters bank and stands at end of line Customer 3 departs; customer 4 begins transaction Customer 4 departs
COMPSCI 105 ADT Queue

Application: Simulation
!!

A time-driven simulation
!! !!

Simulated time is advanced by a single time unit The time of an event, such as an arrival or departure, is determined randomly and compared with a simulated clock

!!

Bank simulation is concerned with arrival events and departure events


!!

Arrival events indicate the arrival at the bank of a new customer


!!

External events: the input file specifies the times at which the arrival events occur

!!

Departure events indicate the departure from the bank of a customer who has completed a transaction
!!

Internal events: the simulation determines the times at which these events occur
COMPSCI 105

41

ADT Queue

Application: Simulation
An event list is needed to implement an event-driven simulation
!! !!

The list keeps track of arrival and departure events that will occur but have not occurred yet The list contains at most one arrival event and one departure event

Fig. 8-15: A
42

typical instance of the event list


COMPSCI 105 ADT Queue

Application: Simulation
!! !!

4 possible configurations of an event list Initially: the event list contains an arrival event A after reading it from the input file but before processing it
!!

Event list: A (initial state)

!!

Generally, the event list contains exactly two events: one arrival event A and one departure event D
!! !!

Event list: D A (general case next event is a departure) Event list: A D (general case next event is an arrival) Event list: A (a departure leaves the tellers line empty) Event list: D (the input has been exhausted)
COMPSCI 105 ADT Queue

!! !!

If the tellers line is empty after the departure (like initial state)
!!

If the end of the input file after processing the arrival event:
!!

43

Simulation with the ADT Queue


+simulate() +processArrival(in arrivalEvent:Event, in arrivalFile: File, inout anEventList: EventList, inout bankQueue: Queue) +processDeparture( in departureEvent: Event, inout anEventList: EventList, inout bankQueue: Queue) +createEventList() +isEmpty(): boolean +insert( in anEvent: Event)
44 COMPSCI 105 ADT Queue

Summary
!!

The definition of the queue operations gives the ADT queue first-in, first-out (FIFO) behaviour A reference-based implementation of a queue uses either
!! !!

!!

A circular linked list A linear linked list with a head reference and a tail reference

!!

An array-based implementation of a queue is prone to rightward drift


!!

A circular array eliminates the problem of rightward drift


COMPSCI 105 ADT Queue

45

Summary
!!

To distinguish between the queue-full and queueempty conditions in a queue implementation that uses a circular array, you can
!! !! !!

Count the number of items in the queue Use a full flag Leave one array location empty

!!

Models of real-world systems often use queues


!!

The event-driven simulation in Chapter 8 of the textbook uses a queue to model a line of customers in a bank
COMPSCI 105 ADT Queue

46

Summary
!!

Simulations:
!! !!

Central to a simulation is the notion of simulated time In a time-driven simulation simulated time is advanced by a single time unit In an event-driven simulation simulated time is advanced to the time of the next event

!!

!!

To implement an event-driven simulation: maintain an event list containing events that have not yet occurred
COMPSCI 105 ADT Queue

47

Вам также может понравиться