使用数组的数据结构,采用Java代码实现双端队列
时间: 2023-05-28 15:04:29 浏览: 132
双端队列(Deque)是一种具有队列和栈的性质的数据结构,它允许从两端插入和删除元素。
Java中提供了Deque接口来实现双端队列,常用的实现类有LinkedList和ArrayDeque。下面是使用数组实现双端队列的Java代码:
```java
public class ArrayDeque<E> {
private E[] data;
private int front;
private int rear;
private int size;
public ArrayDeque(int capacity) {
data = (E[]) new Object[capacity];
front = rear = 0;
size = 0;
}
public ArrayDeque() {
this(10);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void addFirst(E e) {
if (size == data.length) {
resize(2 * data.length);
}
front = (front - 1 + data.length) % data.length;
data[front] = e;
size++;
}
public void addLast(E e) {
if (size == data.length) {
resize(2 * data.length);
}
data[rear] = e;
rear = (rear + 1) % data.length;
size++;
}
public E removeFirst() {
if (isEmpty()) {
throw new IllegalArgumentException("Deque is empty.");
}
E ret = data[front];
data[front] = null;
front = (front + 1) % data.length;
size--;
if (size == data.length / 4 && data.length / 2 != 0) {
resize(data.length / 2);
}
return ret;
}
public E removeLast() {
if (isEmpty()) {
throw new IllegalArgumentException("Deque is empty.");
}
rear = (rear - 1 + data.length) % data.length;
E ret = data[rear];
data[rear] = null;
size--;
if (size == data.length / 4 && data.length / 2 != 0) {
resize(data.length / 2);
}
return ret;
}
public E getFirst() {
if (isEmpty()) {
throw new IllegalArgumentException("Deque is empty.");
}
return data[front];
}
public E getLast() {
if (isEmpty()) {
throw new IllegalArgumentException("Deque is empty.");
}
return data[(rear - 1 + data.length) % data.length];
}
private void resize(int newCapacity) {
E[] newData = (E[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
newData[i] = data[(i + front) % data.length];
}
data = newData;
front = 0;
rear = size;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append(String.format("Deque: size = %d, capacity = %d\n", size, data.length));
res.append("front [");
for (int i = front; i != rear; i = (i + 1) % data.length) {
res.append(data[i]);
if ((i + 1) % data.length != rear) {
res.append(", ");
}
}
res.append("] rear");
return res.toString();
}
}
```
其中,data数组表示队列的容器,front和rear表示队列的头和尾,size表示队列的大小。addFirst方法在队头添加元素,addLast方法在队尾添加元素,removeFirst方法从队头删除元素,removeLast方法从队尾删除元素,getFirst方法获取队头元素,getLast方法获取队尾元素。resize方法用于动态调整数组容量。toString方法用于打印队列的信息。
阅读全文