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 133/** Queue ADT */public interface Queue {}/** Reinitialize the queue. The user is responsible forreclaiming the s<strong>to</strong>rage used by the queue elements. */public void clear();/** Place an element at the rear of the queue.@param it The element being enqueued. */public void enqueue(E it);/** Remove <strong>and</strong> return element at the front of the queue.@return The element at the front of the queue. */public E dequeue();/** @return The front element. */public E frontValue();/** @return The number of elements in the queue. */public int length();Figure 4.22 The Java ADT for a queue.operation) <strong>and</strong> removed from the front (called a dequeue operation). Queues operatelike st<strong>and</strong>ing in line at a movie theater ticket counter. 1 If nobody cheats, thennewcomers go <strong>to</strong> the back of the line. The person at the front of the line is the next<strong>to</strong> be served. Thus, queues release their elements in order of arrival. Accountantshave used queues since long before the existence of computers. They call a queuea “FIFO” list, which st<strong>and</strong>s for “First-In, First-Out.” Figure 4.22 shows a samplequeue ADT. This section presents two implementations for queues: the array-basedqueue <strong>and</strong> the linked queue.4.3.1 Array-Based QueuesThe array-based queue is somewhat tricky <strong>to</strong> implement effectively. A simple conversionof the array-based list implementation is not efficient.Assume that there are n elements in the queue. By analogy <strong>to</strong> the array-basedlist implementation, we could require that all elements of the queue be s<strong>to</strong>red in thefirst n positions of the array. If we choose the rear element of the queue <strong>to</strong> be inposition 0, then dequeue operations require only Θ(1) time because the front elemen<strong>to</strong>f the queue (the one being removed) is the last element in the array. However,1 In Britain, a line of people is called a “queue,” <strong>and</strong> getting in<strong>to</strong> line <strong>to</strong> wait for service is called“queuing up.”

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

Saved successfully!

Ooh no, something went wrong!