查找堆栈的索引 java

Finding index of a stack java

尝试使用堆栈查找最后一个元素输入为 0 的索引,我使用的是 pop() 和 peek() 方法。

这是我的代码:

public class Main {
    public static void main(String[] args) {
        Stack<String> a = new Stack<>();

        a.push("a");
        a.push("b");
        a.push("c");
        a.push("d");
        a.push("e");
        a.push("f");

        System.out.println(a);
        String str = "f";
        int b = 0;
        for (int i = 0; i < a.size(); i++) {
            if (a.peek().equalsIgnoreCase(str)){
                break;
            }
            a.pop();
            b++;
        }
        System.out.println(str);
        System.out.println(b);
    }
}

str = "f" 时的预期输出:

0

是的,当我尝试使用我的解决方案时它工作正常。

直到我尝试使用 str = "b" 预期输出:

[a, b, c, d, e, f]
b
4

实际输出:

[a, b, c, d, e, f]
b
3

同样使用 str = "a", 预期输出:

[a, b, c, d, e, f]
a
5

实际输出:

[a, b, c, d, e, f]
a
3

因此,无论出于何种原因,直到堆栈中的最后两个元素,int b 都没有递增。知道为什么会这样吗?

a.pop() 会变 a.size()。您应该首先将 a.size() 存储为长度,然后开始循环以查找索引。最后,如果第一个输入的元素的索引是0,那么你找到的元素的索引是length - b.

更简单的方法是测试 empty

If not empty then pop Pop returns to top object, so you can then test it.如果匹配则中断。