Safe Enqueuing in an Array

We need to write a safe enqueue() method that will fail when the queue is full. 

Steps for completion:

  1. Modify the enqueue and dequeue methods shown in the preceding code so that the enqueue returns a Boolean value which is false when the queue is full and cannot accept further elements.
  2. Implement the method signatures as follows:
public boolean enqueueSafe(V item)
public Optional<V> dequeueSafe()
  1. The following Snippet 2.26 provides an implementation of the enqueueSafe() method, returning a Boolean value when the queue is full:
private boolean full = false;
public boolean enqueueSafe(V item) {
if (!full) {
array[tailPtr] = item;
tailPtr = (tailPtr + 1) % array.length;
this.full = tailPtr == headPtr;
return true;
}
return false;
}
Snippet 2.26: Safe Enqueue and dequeue solution. Source class name: QueueArray

Go to
https://goo.gl/cBszQL to access the code for implementation of dequeueSafe() method.

We have seen how both queues and stacks can be implemented using a static array structure instead of using the dynamic linked list. This has the advantage of consuming less memory per element as a linked list has to store pointers to other nodes. However, this comes at the cost of having a limit on the structure size.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.106.7