返回堆栈的最小值

时间:2018-02-16 02:12:14

标签: java stack queue

我有一个名为removeMin的方法,它将Stack<CalendarDate>作为参数并从堆栈中删除最小值(在这种情况下是最早的日期)并返回它。但是,我没有得到我预期的价值。我相信我充分了解堆栈。这是我的方法。

public static CalendarDate removeMin(Stack<CalendarDate> stack) {
        Queue<CalendarDate> aux = new LinkedList<CalendarDate>();
        CalendarDate min = stack.peek();
        if(stack.size() < 1) {
            return null;
        }

        while (!stack.empty()) {
            CalendarDate c = stack.pop();
            aux.add(c);
            if(c.compareTo(min) == -1) {
                min = c;
            }
            aux.add(c);
        }

        while (!aux.isEmpty()) {
            if (aux.remove().compareTo(min) == 1) {
                stack.push(aux.remove());
            }
        }

        while (!stack.empty()) {
            aux.add(stack.pop());
        }

        while (!aux.isEmpty()) {
            stack.push(aux.remove());
        }

        return min;

    }

这也是我的main方法中的测试代码。

public static void main(String[] args) {
        // store some dates so they can be reused
        CalendarDate[] store = {new CalendarDate(1,2,10), new CalendarDate(1,1,10), new CalendarDate(12,30,10)};
        Stack<CalendarDate> testAll = new Stack<CalendarDate>();
        for (CalendarDate i: store) {
            testAll.push(i); // build a Stack
        }
        for (int i = 1;i <= 9;i++) {
            testAll.push(new CalendarDate(1,1,10));
        }
        System.out.println(Chapter14.removeMin(testAll));
    }

正如你所看到的,我已经制作了1/1/10,1 / 10/10和12/30/10的筹码。在我运行removeMin方法后,它应该返回12/30/10,因为它在1/1/10之前出现了吗?好吧,我的输出说不然,因为我从removeMin得到1/1/10而不是12/30/10。任何人都可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

如果我错了,请纠正我,但日期似乎是mm / dd / yy格式。如果是这样,那么日期是: 2010年1月2日
2010年1月1日
2010年12月30日

此后又增加了9份 2010年1月1日。

由于1月1日在所有其他日期之前,因此应删除1月1日的1份副本。 要测试这个,您可以尝试循环removeMin,直到堆栈为空。首先应删除1月1日的10份,然后是1月2日,最后是12月30日。