12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

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

Sec. 4.3 Queues 137// Array-based queue implementationclass AQueue implements Queue {private static final int defaultSize = 10;private int maxSize;// Maximum size of queueprivate int front;// Index of front elementprivate int rear;// Index of rear elementprivate E[] listArray; // Array holding queue elements// Construc<strong>to</strong>rsAQueue() { this(defaultSize); }@SuppressWarnings("unchecked") // For generic arrayAQueue(int size) {maxSize = size+1;rear = 0; front = 1;listArray = (E[])new Object[maxSize]; // Create listArray}public void clear(){ rear = 0; front = 1; }// Reinitializepublic void enqueue(E it) { // Put "it" in queueassert ((rear+2) % maxSize) != front : "Queue is full";rear = (rear+1) % maxSize; // Circular incrementlistArray[rear] = it;}public E dequeue() {// Take element out of queueassert length() != 0 : "Queue is empty";E it = listArray[front];front = (front+1) % maxSize; // Circular incrementreturn it;}public E frontValue() { // Get front valueassert length() != 0 : "Queue is empty";return listArray[front];}public int length()// Return length{ return ((rear+maxSize) - front + 1) % maxSize; }Figure 4.25 An array-based queue implementation.

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

Saved successfully!

Ooh no, something went wrong!