Академический Документы
Профессиональный Документы
Культура Документы
Prichard
What is a Queue?
Example: A line to buy a movie ticket Computer applications, e.g. a request to print a document
!!
!!
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
!!
!!
COMPSCI 105
ADT Queue
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
!!
!!
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
}
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
COMPSCI 105
ADT Queue
Applications
!! !!
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
!!
10
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
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
!! !!
13
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
16
COMPSCI 105
ADT Queue
Reference-Based Implementation
!!
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
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
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)
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
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;
!!
!!
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
!!
!!
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
Array-Based Implementation
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:
Fig.8-13
30 COMPSCI 105 ADT Queue
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
!!
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
!!
!!
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
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
!!
!!
!!
!!
36
Application: Simulation
!!
!!
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
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
!!
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
!!
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
!!
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
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
!!
!!
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
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
!!
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
!!
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