Download presentation
Presentation is loading. Please wait.
1
Queues
2
… frontrear dequeueenqueue
8
Message 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. Program #1 Program #2 front rear Send a message to the queue Take a message from the queue
14
The Queue Abstract Data Type
16
This table shows a series of queue operations and their effects. The queue is empty initially. 5 5 3 3
18
A Queue Interface in Java
19
A Simple Array-Based Implementation To implement a queue with an array, we need: 1.An array of the size N 2.An index f for the front element 3.An index r for next empty slot or cell Q: … 012 r N - 1 f
20
As objects are enqueued and dequeued, the queue moves along in the array. For example: fr After enqueue: f r After dequeue: f r
22
When 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 12 rf N - 1
23
Initially, we assign r = f = 0, indicating that the queue is empty. During the process, we may meet a situation where r = f = i (0 < i < N), which also indicates the queue is empty. Now we assume that we enqueue N objects into Q without dequeueing any of them: Q: … 012 r f N - 1 Then, we have r = f = 0. But in this case, we have a full queue. In general, when r = f = i (0 < i < N), it is possible that we have a full queue.
24
Problem: 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.
25
Algorithms: size(): return the number (N - f + r) mod N 012N-1N+r-1 If r f, then r - f 0 N + (r - f ) N (N - f + r) mod N = - f + r = r - f If r 0 N - f + r = N – (f - r ) < N (N - f + r) mod N = N - f + r
26
Algorithms: isEmpty( ): return the result of the evaluation of the relationship f = r f r
27
Algorithms: front( ): if the queue is empty throw a QueueEmptyException else return element Q[f] Q: … 012 r N - 1 f
28
enqueue(o): if queue size is N - 1 throw a QueueFullException else store the object to Q[r] assign (r + 1) mod N to r Q: … 012 r N - 1 f (r + 1) mod N
29
dequeue( ): if queue size is empty throw a QueueEmptyException else save the element Q[f] to a variable temp make the element Q[f] a null object assign (f + 1) mod N to f Q: … 012 r N - 1 f (f + 1) mod N
30
Memory Allocation in Java
33
Data Structure Exercises 4.1
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.