java - 如何使用动态数组删除元素?
问题描述
我目前正在执行我的任务,即模拟队列代码,其中一种方法是
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
解决方案
我查看了您的队列并评论说:
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
}
}
推荐阅读
- r - 在R中按元素拆分和组合大量列表
- java - 在服务器上运行spring应用并离开(nohup错误)
- python - 如何在 django rest 框架中使用 image_id 和 image_id 作为参数来删除图像
- c# - 如果列表为空,则返回与所有提供的参数匹配的记录
- angular - NullInjectorError: R3InjectorError(AppModule)[RouterModule -> Router -> Function -> Function ->Function]: NullInjectorError: No provider for Function
- google-chrome - 为什么调试器会影响 Chrome 浏览器中微任务的执行顺序?
- python - 导入 keras 时出错:AttributeError:模块“tensorflow.compat.v2.__internal__”没有属性“register_clear_session_function”
- css - 仅将单个 CSS 属性应用于 Chrome?
- angularjs - Angular JS 中的条形图使用 Chartjs
- celery - Celery beat_schedule 仅在删除以前的 celerybeat-schedule 文件后才有效