Data Structures and Algorithms-Queues
Data Structures and Algorithms-Queues
Queues
Queue ADT
queue: A list with the restriction that insertions are done at
one end and deletions are done at the other
First-In, First-Out ("FIFO”)
Elements are stored in order of
insertion but don't have indexes.
Client can only add to the end of the
queue, and can only examine/remove
the front of the queue.
Programming:
modeling a line of customers or clients
storing a queue of computations to be performed in order
Q: 0 size - 1
b c d e f
front back
Circular Array Queue
Q: 0 size - 1
b c d e f
front back
// Basic idea only!
enqueue(x) {
Q[back] = x;
back = (back + 1) % size
}
front back
b c d e f
front back
String Queue Interface
/**
* Interface for a queue of Strings.
*/
public interface StrQueue {
/**
* Tests if the queue is empty.
*/
public boolean isEmpty();
/**
* Inserts an element at the end of the queue.
*/
public void enqueue(String str);
/**
* Deletes and returns the element at the front of the queue.
* @return the deleted value; throws NoSuchElementException if empty
*/
public String dequeue();
}
Generic Queue Interface
/**
* Interface for a queue.
*/
public interface Queue<E> {
/**
* Tests if the queue is empty.
*/
public boolean isEmpty();
/**
* Inserts an element at the end of the queue.
*/
public void enqueue(E e);
/**
* Deletes and returns the element at the front of the queue.
* @return the deleted value; throws NoSuchElementException if empty
*/
public E dequeue();
}