Deques and Randomized Queues
Deque.java
双向队列,因为要求所有操作的复杂度为 O ( 1 ) O(1) O(1),采用双向链表进行实现。
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private Node first = null;
private Node last = null;
private int size = 0;
// construct an empty deque
public Deque() {
}
// is the deque empty?
public boolean isEmpty() {
return first == null;
}
// return the number of items on the deque
public int size() {
return size;
}
// add the item to the front
public void addFirst(Item item) {
if (item == null) {
throw new IllegalArgumentException();
}
size++;
Node old = first;
first = new Node();
first.item = item;
// 若原队列为空需要进行特殊处理
if (old == null) {
last = first;
return;
}
first.next = old;
old.prev = first;
}
// add the item to the back
public void addLast(Item item) {
if (item == null) {
throw new IllegalArgumentException();
}
size++;
Node old = last;
last = new Node();
last.item = item;
// 若原队列为空需要进行特殊处理
if (old == null) {
first = last;
return;
}
old.next = last;
last.prev = old;
}
// remove and return the item from the front
public Item removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException();
}
Node temp = first;
first = first.next;
// 若移除后为空队列需要进行特殊处理
if (first == null)