Как удалить элемент с массивом Dynami c? - PullRequest
1 голос
/ 07 февраля 2020

В настоящее время я выполняю свое задание, которое состоит в том, чтобы выполнить имитацию кода очереди, один из методов - 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

1 Ответ

0 голосов
/ 07 февраля 2020

Я посмотрел на вашу очередь и прокомментировал:

    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
    }

}
...