Home > Back-end >  Finding index of a stack java
Finding index of a stack java

Time:09-28

Trying to find the index with the last element inputted as 0 using stack, I'm using the method pop(), and peek().

Here is my code:

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);
    }
}

Expected output if str = "f":

0

and yes, when I tried using my solution it works properly.

Until I tried using str = "b" Expected output:

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

Actual output:

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

Also using str = "a", Expected output:

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

Actual output:

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

So for whatever reason until the last two elements on the stack, int b didn't get incremented. Any idea on why this happens?

CodePudding user response:

a.pop() will change a.size(). You should store a.size() as length at first and begin loop to find index. Finally, if the index of first inputted element is 0, then the index of element you find is length - b.

CodePudding user response:

A simpler way would be to test for empty

If not empty then pop Pop returns to top object, so you can then test it. If it matches then break.

  • Related