CSE 373 Data Structures and Algorithms: Lecture 2: Queues
CSE 373 Data Structures and Algorithms: Lecture 2: Queues
2
Queues in computer science
Operating systems:
queue of print jobs to send to the printer
queue of programs / processes to be run
queue of network data packets to send
Programming:
modeling a line of customers or clients
storing a queue of computations to be performed in order
3
Using Queues
add(value) places given value at back of queue
remove() removes value from front of queue and returns it;
throws a NoSuchElementException if queue is empty
peek() returns front value from queue without removing it;
returns null if queue is empty
size() returns number of elements in queue
isEmpty() returns true if queue has no elements
Queue<Integer> q = new LinkedList<Integer>();
q.add(42);
q.add(-3);
q.add(17); // front [42, -3, 17] back
System.out.println(q.remove()); // 42
4
Queue idioms
As with stacks, must pull contents out of queue to view them.
while (!q.isEmpty()) {
do something with q.remove();
}
5
Implementing Queue ADT: Array Queue
Keep track of the number of elements in the queue,
size.
Enqueue at the back of the array (size).
Dequeue at the front of the array (index 0).
6
Implementing Queue ADT:
Circular Array Queue
Q: 0 size - 1
b c d e f
front back
7
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
}
// Basic idea only!
dequeue() {
x = Q[front];
front = (front + 1) % size;
return x;
}
8
Linked List Queue
b c d e f
front back
10
Exercise: Linked List Queue Implementation
Implement a queue class that stores String values using a
singly linked list with both nodes to indicate the front and
the back of the queue as below. The queue should
implement the interface on the next slide.
b c d e f
front back
11
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();
}
12
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();
}
13