使用数组+奇数和偶数在Java中出列

时间:2018-05-03 15:15:12

标签: java arrays arraydeque

我在编程练习中遇到了一些问题,我应该使用数组实现dequeues。

我已经完成了我需要的操作但是在实现之后你应该运行数字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

1 个答案:

答案 0 :(得分:1)

你只是错误使用 - 运营商。 addFront方法的正确实现应该是:

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!");
}

所以,区别在于 deque [ - head] = x ;

- 头部表示将头部值减1,然后使用它。

head--表示使用值head然后降低其值

你的情况是:

  1. head = deque.length-1; head == 19

  2. head!= 0然后你去了else语句。 head value = 19.你使用了head--再次获得19并将其减1,但必须使用--head。