【发布时间】:2017-09-22 00:46:31
【问题描述】:
我正在使用arraylist 来实现一个队列。一切都很好,除了当我尝试找到队列的最小值时它不能正常工作并且出队和窥视功能由于某种原因不能按预期工作。我尝试逐行查看,但我不明白 min() 函数出了什么问题:
public class queuePractice {
static ArrayList<Integer>nums = new ArrayList<Integer>();
static int top = -1;
public static void main(String[] args) {
enqueue(5);
enqueue(2);
enqueue(6);
enqueue(3);
enqueue(12);
enqueue(1);
enqueue(20);
System.out.println("The min is: " + min());
}
public static int peek() {
return nums.get(0);
}
public static void enqueue(int x) {
nums.add(++top, x);
}
public static int dequeue() {
top--;
return nums.remove(0);
}
public static void display() {
for(int x = 0; x <=top; x++) {
System.out.print(nums.get(x) + " ");
}
System.out.println();
}
public static boolean isEmpty() {
return top==-1;
}
public static int min() {
int min = Integer.MAX_VALUE;
while(min > peek()) {
min = peek();
dequeue();
}
return min;
}
}
即使我将 while 循环更改为 for 循环,peek 函数也会一遍又一遍地返回 2。出于某种原因,每当我将其出队时,它都不会更新其值?但是逐行浏览我无法理解问题所在。
【问题讨论】: