23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The implementation above conta<strong>in</strong>s an important detail, which might be missed at<br />

first. Consider the situation that occurs if we enqueue N objects <strong>in</strong>to Q without<br />

dequeu<strong>in</strong>g any of them. We would have f = r, which is the same condition that<br />

occurs when the queue is empty. Hence, we would not be able to tell the<br />

difference between a full queue <strong>and</strong> an empty one <strong>in</strong> this case. Fortunately, this is<br />

not a big problem, <strong>and</strong> a number of ways for deal<strong>in</strong>g with it exist.<br />

The solution we describe here is to <strong>in</strong>sist that Q can never hold more than N − 1<br />

objects. This simple rule for h<strong>and</strong>l<strong>in</strong>g a full queue takes care of the f<strong>in</strong>al problem<br />

with our implementation, <strong>and</strong> leads to the pseudo-coded descriptions of the queue<br />

methods given <strong>in</strong> Code Fragment 5.14. Note our <strong>in</strong>troduction of an<br />

implementation-specific exception, called FullQueueException, to signal<br />

that no more elements can be <strong>in</strong>serted <strong>in</strong> the queue. Also note the way we<br />

compute the size of the queue by means of the expression (N − f + r) mod N,<br />

292

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!