首页 > 解决方案 > 如何使用动态数组删除元素?

问题描述

我目前正在执行我的任务,即模拟队列代码,其中一种方法是 Dequeue()返回队列头然后将其删除,我的老师建议我使用我的 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

标签: javaarraysoopdynamicimplementation

解决方案


我查看了您的队列并评论说:

    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
    }

}

推荐阅读