You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java数组实现Deque编程练习求助:奇偶数字入队与输出问题

Troubleshooting Your Array-Based Deque Implementation in Java

Hey there! Let's figure out what's tripping up your array-based deque in Java. You've already got the core operations implemented, so the issue is probably in how you're handling the insertion logic or the removeFront method's behavior. Let's break this down step by step:

First, Double-Check Your Insertion Methods

Make sure your addFront and addLast methods are correctly managing the deque's structure:

  • If you're using a circular array approach (the most efficient for deques), verify you're updating the front/back indices with modulo arithmetic to handle wrap-around. For addFront, you need to adjust the front index backward (with a buffer to avoid negative numbers, like (front - 1 + arrayLength) % arrayLength).
  • If you're using a non-circular array (shifting elements when adding to front), ensure addFront shifts all existing elements to the right by one position before placing the new element at index 0. A common mistake here is overwriting elements instead of shifting, or shifting in the wrong direction.

Verify Your Loop Logic

Let's recap the expected insertion flow for 1-20:

  • Odd numbers (1,3,...,19) go to the front: each new odd pushes the previous front elements further back.
  • Even numbers (2,4,...,20) go to the tail: they append in order after the existing even numbers.

By the end of the loop, your deque should look like [19,17,...,1,2,4,...,20] from front to tail. If your output is jumbled, your addFront might be appending instead of prepending, or your indices are flipped.

Check Your removeFront Implementation

Ensure removeFront is correctly pulling elements from the front of the deque and updating the deque's state:

  • For circular arrays: update the front index to (front + 1) % arrayLength after removing the element, and decrement the size.
  • For non-circular arrays: shift all remaining elements left by one position after removing the first element.

Example Working Implementation

Here's a snippet of a circular array deque that should produce your expected output, so you can compare it to your code:

public class ArrayDeque<T> {
    private T[] items;
    private int front;
    private int size;
    private static final int INITIAL_CAPACITY = 8;

    public ArrayDeque() {
        items = (T[]) new Object[INITIAL_CAPACITY];
        front = 0;
        size = 0;
    }

    private int getLastIndex() {
        return (front + size - 1) % items.length;
    }

    public void addFront(T item) {
        if (size == items.length) {
            resize();
        }
        // Adjust front index backward with wrap-around
        front = (front - 1 + items.length) % items.length;
        items[front] = item;
        size++;
    }

    public void addLast(T item) {
        if (size == items.length) {
            resize();
        }
        int nextLast = (getLastIndex() + 1) % items.length;
        items[nextLast] = item;
        size++;
    }

    public T removeFront() {
        if (size == 0) {
            return null; // Or throw an exception if preferred
        }
        T removed = items[front];
        items[front] = null;
        // Move front index forward with wrap-around
        front = (front + 1) % items.length;
        size--;
        return removed;
    }

    private void resize() {
        T[] newItems = (T[]) new Object[items.length * 2];
        for (int i = 0; i < size; i++) {
            newItems[i] = items[(front + i) % items.length];
        }
        items = newItems;
        front = 0;
    }

    public static void main(String[] args) {
        ArrayDeque<Integer> deque = new ArrayDeque<>();
        // Populate the deque
        for (int i = 1; i <= 20; i++) {
            if (i % 2 != 0) {
                deque.addFront(i);
            } else {
                deque.addLast(i);
            }
        }
        // Remove and print all elements
        System.out.print("(");
        Integer item;
        boolean firstElement = true;
        while ((item = deque.removeFront()) != null) {
            if (!firstElement) {
                System.out.print(",");
            }
            System.out.print(item);
            firstElement = false;
        }
        System.out.println(")");
    }
}

Running this code will output exactly what you expect: (19,17,15,13,11,9,7,5,3,1,2,4,6,8,10,12,14,16,18,20)

内容的提问来源于stack exchange,提问作者bschne11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:47:14