How to get true LIFO order, out of the stack?

517 Views Asked by At

How to add int values and then iterate through stack getting LIFO order? Adding 7 and 1 returns 7 and 1.

   public void calculate_10to99() {

    Stack romanNumeralsStack =  new Stack();
        romanNumeralsStack.add(7);
        romanNumeralsStack.add(1);

        Iterator value = romanNumeralsStack.iterator();

    while (value.hasNext()){
        System.out.println(value.next());
    }
2

There are 2 best solutions below

2
On

Do it like this:

public void calculate_10to99() {

    Stack<Integer> romanNumeralsStack =  new Stack<>();
        romanNumeralsStack.push(7);
        romanNumeralsStack.push(1);

    while (!romanNumeralsStack.empty()){
        System.out.println(romanNumeralsStack.pop());
    }
 }

The iterator() method comes from its superclass Vector and just returns all of the elements in order, so iterator.next() does not give you LIFO

0
On

You are using iterator as

Iterator value = romanNumeralsStack.iterator();

Which return element in random order from what was present in the stack.

You should use another method such as. This will check if the stack is not empty then it keeps on popping element from the top which makes it LIFO.

public static void calculate_10to99() {

        Stack romanNumeralsStack = new Stack();
        romanNumeralsStack.add(7);
        romanNumeralsStack.add(1);

        while (!romanNumeralsStack.isEmpty()){
            System.out.println(romanNumeralsStack.pop());

        }
    }