如何使用动态数组删除元素?

问题描述 投票:0回答:1

我目前正在完成我的任务,该任务是模拟队列代码,其中一种方法是Dequeue()返回队列的头然后将其删除,我的老师建议我的出队与我的enqueue()方法类似,因为您可以观察到我已经编写了代码,希望有人可以建议我如何终止它。

import java.util.NoSuchElementException;

public class MyQueue implements IntQueue {

    int[] heltal;

    public MyQueue() {
        heltal = new int[0];
    }

    public void enqueue(int tal) {

        int[] temp = new int[heltal.length + 1];

        for (int x = 0; x < heltal.length; x++) {
            heltal[x] = temp[x] + tal;

        }
        heltal = temp;

        for (int i = 0; i < heltal.length; i++) {
            heltal[i] = tal;
        }

    }

    public int dequeue() throws NoSuchElementException {
        if (empty()) {
            throw new NoSuchElementException("The Queue is empty, there is nothing to dequeue");

        } else {

            int[] temp = new int[heltal.length - 1];

            for (int i = 0; i < heltal.length; i++) {
                heltal[i] = temp[i];

            }
            heltal = temp;

            for (int i = 0; i < heltal.length; i++) {


            }

        }
        return heltal[0];
    }

    @Override
    public int peek() throws NoSuchElementException {
        if (empty()) {
            throw new NoSuchElementException("The Queue is empty");
        } else {
            return heltal[0];
        }

    }

    @Override
    public boolean empty() {
        return heltal.length == 0;

    }
}

我的出队应该像这样工作

[4] [3] [5] [7] before dequeue 4 indexes
[3] [5] [7] after dequeue 3 indexes
java arrays oop dynamic implementation
1个回答
0
投票

我看着你的入队并发表了评论:

    public void enqueue(int tal) {

    int[] temp = new int[heltal.length + 1];

    for (int x = 0; x < heltal.length; x++) { //this goes through all the elemeents of heltal
        heltal[x] = temp[x] + tal; //this would set 0 from the new temp + tal to all values

    }
    heltal = temp; // here you write the temp array over the heltal, which was zero

    for (int i = 0; i < heltal.length; i++) {
        heltal[i] = tal; //here you write heltal all over it once again
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.