Exercise 10.1-4

Rewrite ENQUEUE and DEQUEUE to detect underflow and overflow of a queue.

REWRITTEN-ENQUEUE(Q, x)

1 if Q.tail + 1 == Q.head or (Q.tail == Q.length and Q.head == 1):

2     error "overflow"

3 Q[Q.tail] = x

4 if Q.tail == Q.length:

5     Q.tail = 1

6 else Q.tail = Q.tail + 1

REWRITTEN-DEQUEUE(Q)

1 if Q.tail == Q.head:

2     error "underflow"

3 x = Q[Q.head]

4 if Q.head == Q.length:

5     Q.head = 1

6 else Q.head = Q.head + 1

7 return x