我目前正在做我的任务,这是为了模拟队列代码,方法之一是
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
答案 0 :(得分: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
}
}