我想在这里使用圆形阵列来实现双端队列为我的代码(抱歉张贴整个班级)调整大小的圆形阵列,在双端队列实施
public class Deque<Item> implements Iterable<Item> {
private int frontIndex;
private int backIndex;
private static final int defaulSize = 8;
private int size;
private Item holder[];
private int capacity;
public Deque() {
holder = (Item[]) new Object[defaulSize];
this.size = 0;
this.frontIndex = 0;
this.backIndex = 0;
this.capacity = defaulSize;
}
public boolean isEmpty() {
return this.size == 0;
}
public int size() {
return this.size;
}
public void addFirst(Item item) throws Exception {
if (item == null) {
throw new NoSuchElementException();
}
if (size == capacity) {
doubleCapacity();
}
holder[this.frontIndex] = item;
this.frontIndex = Math.floorMod((this.frontIndex + 1), capacity);
size++;
}
public void addLast(Item item) throws Exception {
if (item == null) {
throw new NoSuchElementException();
}
if (size == capacity) {
doubleCapacity();
}
holder[this.backIndex] = item;
this.backIndex = Math.floorMod((this.backIndex - 1), capacity);
size++;
}
public Item removeFirst() throws Exception {
if (isEmpty()) {
throw new Exception("Deque is empty.");
}
this.frontIndex = Math.floorMod((this.frontIndex - 1), capacity);
this.size--;
Item e = holder[this.frontIndex];
holder[this.frontIndex] = null;
return e;
}
public Item removeLast() throws Exception {
if (isEmpty()) {
throw new Exception("Deque is empty.");
}
this.backIndex = Math.floorMod((this.backIndex + 1), capacity);
this.size--;
Item e = holder[this.backIndex];
holder[this.backIndex] = null;
return e;
}
private void doubleCapacity() {
int p = this.backIndex;
int n = holder.length;
int r = n - p; // number of elements to the right of p
capacity = (n) * 2;
Object[] a = new Object[capacity];
System.arraycopy(holder, p, a, 0, r);
System.arraycopy(holder, 0, a, r, p);
holder = (Item[]) a;
this.backIndex = n;
this.frontIndex = 0;
}
private class DequeIterator<E> implements Iterator<E> {
private int pos = 0;
public boolean hasNext() {
return holder.length > pos;
}
public E next() {
return (E) holder[pos++];
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove an element of an array.");
}
}
@Override
public Iterator<Item> iterator() {
return this.new DequeIterator<Item>();
}
}
的问题来了,当我试图调整用双端队列圆阵,好像所有的指标都得到搞砸
我用类似于它的Java实现如何完成这种方法进行实验
private void doubleCapacity() {
int p = this.backIndex;
int n = holder.length;
int r = n - p; // number of elements to the right of p
capacity = (n) * 2;
Object[] a = new Object[capacity];
System.arraycopy(holder, p, a, 0, r);
System.arraycopy(holder, 0, a, r, p);
holder = (Item[]) a;
this.backIndex = n;
this.frontIndex = 0;
}
有没有对如何,如果它作为双端队列调整大小的圆形阵列,或者我如何可以调整此双端以特定的方式
(如果不是一门功课只是个人的研究)
如果你调用'addFirst'然后'addLast',第一个元素将被覆盖。 –