6
circular queue

Circular queue. Array-based Queue Use an array of size N in a circular fashion Three variables keep track of the front, rear, and size f index of the

Embed Size (px)

Citation preview

Page 1: Circular queue. Array-based Queue Use an array of size N in a circular fashion Three variables keep track of the front, rear, and size f index of the

circular queue

Page 2: Circular queue. Array-based Queue Use an array of size N in a circular fashion Three variables keep track of the front, rear, and size f index of the

Array-based Queue

• Use an array of size N in a circular fashion• Three variables keep track of the front, rear, and size

f index of the front elementr index immediately past the rear element, where

we add new elements (enqueue)size is number of entries in the queue

Page 3: Circular queue. Array-based Queue Use an array of size N in a circular fashion Three variables keep track of the front, rear, and size f index of the

3

Array-based Queue

Q

0 1 2 rf

normal configuration

Q

0 1 2 fr

wrapped-around configuration

ADS Lecture 11

• Use an array of size N in a circular fashion• Three variables keep track of the front, rear, and size

f index of the front elementr index immediately past the rear element, where

we add new elements (enqueue)size is number of entries in the queue

Page 4: Circular queue. Array-based Queue Use an array of size N in a circular fashion Three variables keep track of the front, rear, and size f index of the

4

Queue Operations• We use the modulo operator (remainder of division)

Algorithm size()return size

Algorithm isEmpty()return size == 0

Q0 1 2 rf

Q0 1 2 fr

ADS Lecture 11

• Operation enqueue throws an exception if the array is full

This exception is implementation-dependent

Algorithm enqueue(o)if size() = N then

throw FullQueueException else

Q[r] or (r + 1) mod N

update size!size++

Page 5: Circular queue. Array-based Queue Use an array of size N in a circular fashion Three variables keep track of the front, rear, and size f index of the

5

Queue Operations (cont.)

• Operation dequeue throws an exception if the queue is empty

• This exception is specified in the queue ADT

Algorithm dequeue()if isEmpty() then

throw EmptyQueueException else

o Q[f]f (f + 1) mod Nreturn o

ADS Lecture 11

Pros and cons of array based implementation:Again: quick and easy, all methods run in constant timeBut again, need good idea of capacity a priori

update size!size--

Page 6: Circular queue. Array-based Queue Use an array of size N in a circular fashion Three variables keep track of the front, rear, and size f index of the

Your mission

See assessed exercise 2