11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sec. 4.3 Queues 129/** Array-based queue implement<strong>at</strong>ion */class AQueue implements Queue {priv<strong>at</strong>e st<strong>at</strong>ic final int defaultSize = 10;priv<strong>at</strong>e int maxSize;// Maximum size of queuepriv<strong>at</strong>e int front;// Index of front elementpriv<strong>at</strong>e int rear;// Index of rear elementpriv<strong>at</strong>e E[] listArray; // Array holding queue elements/** Constructors */AQueue() { this(defaultSize); }@SuppressWarnings("unchecked") // For generic arrayAQueue(int size) {maxSize = size+1;// One extra space is alloc<strong>at</strong>edrear = 0; front = 1;listArray = (E[])new Object[maxSize]; // Cre<strong>at</strong>e listArray}/** Reinitialize */public void clear(){ rear = 0; front = 1; }/** Put "it" in queue */public void enqueue(E it) {assert ((rear+2) % maxSize) != front : "Queue is full";rear = (rear+1) % maxSize; // Circular incrementlistArray[rear] = it;}/** Remove <strong>and</strong> return front value */public E dequeue() {assert length() != 0 : "Queue is empty";E it = listArray[front];front = (front+1) % maxSize; // Circular incrementreturn it;}/** @return Front value */public E frontValue() {assert length() != 0 : "Queue is empty";return listArray[front];}/** @return Queue size */public int length(){ return ((rear+maxSize) - front + 1) % maxSize; }Figure 4.27 An array-based queue implement<strong>at</strong>ion.

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

Saved successfully!

Ooh no, something went wrong!