Data Stuctures
Abstract Data Types
Stacks are Last In, First Out (LIFO):
Often items should be processed in the order they arrive:
Examples:
InputStream in
, in.get()
reads characters in orderAnother abstract data type: the queue
Supports two basic operations:
void enq(T item)
enqueue (add) an item to the end of the queueT deq()
dequeue (remove) item from the front queue and return itThe first item enqueued is the first to be dequeued, etc
How could we implement a queue with a linked list?
QueueList
public interface SimpleQueue<T> {
// Enqueue item to the queue
void enq(T item);
//Dequeue (i.e., remove and return) the first item in the queue. Returns null if the queue is currently empty
T deq();
// Determine if the queue is currently empty
boolean isEmpty();
}
public class QueueList<T> implements SimpleQueue<T>, Iterable<T> {
private Node head = null;
private Node tail = null;
@Override
public void enq(T item) {
Node nd = new Node(item);
if (head == null) {
head = nd;
tail = nd;
return;
}
tail.next = nd;
tail = nd;
}
@Override
public T deq() {
if (head == null) {
return null;
}
T item = head.item;
head = head.next;
return item;
}
@Override
public boolean isEmpty() {
return (head == null);
}
public T peek() {
if (head == null) {
return null;
}
return head.item;
}
class Node {
private Node next;
private T item;
public Node(T item) {
this.item = item;
}
}
public Iterator<T> iterator() {
return new ListIterator();
}
class ListIterator implements Iterator<T> {
Node curr;
public ListIterator() {
curr = head;
}
public boolean hasNext() {
return (curr != null);
}
public T next() {
if (curr == null) {
return null;
}
T item = curr.item;
curr = curr.next;
return item;
}
}
}
Setup:
Initially, person 1 is manicurist.
Josephus does not want a manicure!
Question. Where should Josephus sit at the table to ensure that he does not receive a manicure?
Devise a procedure for determining where Josephus should sit to avoid a manicure
Use a queue!
getSize()
method