Title: Queues
1Queues
2front
rear
dequeue
enqueue
3(No Transcript)
4(No Transcript)
5(No Transcript)
6(No Transcript)
7(No Transcript)
8Message queues in an operating system There are
times that programs need to communicate with
each other. Unix operating system provides
message queue as one of the mechanisms to
facilitate communication.
Send a message to the queue
Program 1
rear
Take a message from the queue
Program 2
front
9(No Transcript)
10(No Transcript)
11(No Transcript)
12(No Transcript)
13(No Transcript)
14The Queue Abstract Data Type
15(No Transcript)
16This table shows a series of queue operations and
their effects. The queue is empty initially.
5
5 3
3
17(No Transcript)
18A Queue Interface in Java
19A Simple Array-Based Implementation
- To implement a queue with an array, we need
-
- An array of the size N
- An index f for the front element
- An index r for next empty slot or cell
Q
0
1
2
r
N - 1
20As objects are enqueued and dequeued, the queue
moves along in the array. For example
f
r
After enqueue
r
f
After dequeue
r
f
21(No Transcript)
22When we increment f or r, we compute the result
as (f 1) mod N or (r 1) mod N . In Java, the
modulo operator is (remainder operator). For
example, if r N - 1, then (r 1) N ,
therefore, (r 1) mod N 0 The value of r
wraps around from N to 0.
Q
0
1
2
N - 1
r
f
23Initially, we assign r f 0, indicating that
the queue is empty. During the process, we may
meet a situation where r f i (0 lt i lt
N), which also indicates the queue is empty. Now
we assume that we enqueue N objects into Q
without dequeueing any of them
0
1
2
N - 1
Q
r
f
Then, we have r f 0. But in this case, we
have a full queue. In general, when r f i (0
lt i lt N), it is possible that we have a full
queue.
24Problem r f may indicate that the queue is
empty or that the queue is full. Solution when
r f N 1, report that the queue is full.
25Algorithms size() return the number (N - f
r) mod N
0
1
2
N-1
Nr-1
If r ? f, then r - f ? 0
N (r - f ) ? N
(N - f r) mod N - f r r - f
If r lt f, then f - r gt 0
N - f r N (f - r ) lt N
(N - f r) mod N N - f r
26Algorithms isEmpty( ) return the result of
the evaluation of the relationship f r
f
r
27Algorithms front( ) if the queue is
empty throw a QueueEmptyException else
return element Qf
28enqueue(o) if queue size is N - 1 throw a
QueueFullException else store the object to
Qr assign (r 1) mod N to r
(r 1) mod N
29dequeue( ) if queue size is empty throw a
QueueEmptyException else save the element Qf
to a variable temp make the element Qf a
null object assign (f 1) mod N to f
(f 1) mod N
Q
0
1
2
r
N - 1
f
30Memory Allocation in Java
31(No Transcript)
32(No Transcript)
33Data Structure Exercises 4.1