📅  最后修改于: 2023-12-03 15:39:08.315000             🧑  作者: Mango
ArrayDeque 是 Java 集合框架中的一个双端队列实现。它可以用作栈和队列,因为它允许从两端添加和删除元素,而不需要移动其他元素。
在本文中,我们将介绍如何实现 ArrayDeque API 的 Java 程序。
接下来的代码实现展示了如何实现 ArrayDeque API 的 Java 程序。
public class ArrayDeque<T> {
private Object[] elements;
private int front;
private int rear;
private int size;
private static final int DEFAULT_CAPACITY = 10;
public ArrayDeque() {
elements = new Object[DEFAULT_CAPACITY];
front = rear = -1;
size = 0;
}
public void addFirst(T value) {
if (isFull()) {
resize();
}
if (front == -1) {
front = rear = 0;
} else if (front == 0) {
front = elements.length - 1;
} else {
front--;
}
elements[front] = value;
size++;
}
public void addLast(T value) {
if (isFull()) {
resize();
}
if (rear == -1) {
front = rear = 0;
} else if (rear == elements.length - 1) {
rear = 0;
} else {
rear++;
}
elements[rear] = value;
size++;
}
public T removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException("Deque is empty");
}
T element = (T) elements[front];
if (front == rear) {
front = rear = -1;
} else {
if (front == elements.length - 1) {
front = 0;
} else {
front++;
}
}
size--;
return element;
}
public T removeLast() {
if (isEmpty()) {
throw new NoSuchElementException("Deque is empty");
}
T element = (T) elements[rear];
if (front == rear) {
front = rear = -1;
} else if (rear == 0) {
rear = elements.length - 1;
} else {
rear--;
}
size--;
return element;
}
public T getFirst() {
if (isEmpty()) {
throw new NoSuchElementException("Deque is empty");
}
return (T) elements[front];
}
public T getLast() {
if (isEmpty()) {
throw new NoSuchElementException("Deque is empty");
}
return (T) elements[rear];
}
public boolean isEmpty() {
return size == 0;
}
private boolean isFull() {
return size == elements.length;
}
public void clear() {
elements = new Object[DEFAULT_CAPACITY];
front = rear = -1;
size = 0;
}
private void resize() {
int length = elements.length;
Object[] newElements = new Object[length * 2];
int tmpFront = front, i = 0;
do {
newElements[i++] = elements[tmpFront];
if (tmpFront == length - 1) {
tmpFront = 0;
} else {
tmpFront++;
}
} while (tmpFront != rear + 1);
elements = newElements;
front = 0;
rear = length - 1;
}
}
在本文中,我们介绍了如何实现 ArrayDeque API 的 Java 程序。我们实现了 addFirst()、addLast()、removeFirst()、removeLast()、getFirst()、getLast()、isEmpty() 和 clear() 方法,并展示了代码实现。
实现 ArrayDeque API 可能更复杂,因为还有许多其他功能要实现(如迭代器支持),但是本文讨论的主要点应该可以让你开始进行构建。