我的编程练习遇到了一些麻烦,我应该使用数组实现出队。
我已经得到了我需要的操作,但是在实现之后你应该遍历数字 1-20 并在出队的末尾插入偶数,奇数添加开头。
之后,您应该使用removeFront 方法删除列表中的所有数字,并将它们打印在控制台上。
还有提示正确的输出是:(19,17,15...,1,2,4,...,20)。
我现在的问题是列表中缺少数字 1,而是打印出一个空值作为要删除的第一个项目。
public class Dequeues<E> {
private final int max;
private int head;
private int tail;
private E[] deque;
private int counter;
public Dequeues(int max) {
this.max = max;
deque = (E[]) new Object[max];
this.head = 0;
this.tail = 0;
this.counter = 0;
}
public boolean isEmpty (){
return (counter == 0);
}
public boolean isFull() {
return(counter>= max);
}
public void addFront (E x){
if(!isFull()) {
if (head == 0) {
head = deque.length-1;
deque[head] = x;
} else {
deque[head--] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public void addBack(E x){
if(!isFull()) {
if(tail == deque.length-1) {
tail = 0;
deque[tail] = x;
} else {
deque[tail++] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public E removeFront(){
if(!isEmpty()) {
E ret = deque[head];
deque[head++] = null;
if(head >= deque.length) {
head = 0;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public E removeBack(){
if (!isEmpty()) {
E ret = deque[tail];
deque[tail--] = null;
if(tail < 0) {
tail = deque.length-1;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public static void main (String [] args) {
Dequeues test = new Dequeues(20);
for (int i = 1; i <= test.deque.length; i++) {
if(i % 2 == 0) {
test.addBack(i);
} else if(i % 2 == 1) {
test.addFront(i);
}
}
System.out.println("Use of removeFront and output of the values: ");
for (int i = 0; i < test.deque.length; i++) {
System.out.print(test.removeFront() + " ");
}
}}
输出如下:
使用 removeFront 和输出值:null 19 17 15 13 11 9 7 5 3 2 4 6 8 10 12 14 16 18 20