javastacklifo

How can I show the content of a LIFO stack without deleting the content in Java?


I'm trying to create a 'history' kind of feature that follows the LIFO characteristics. Last Input First Output.

So the user will introduce some words that will be stored in a stack for printing them afterwords. The program, summarized, looks like this:

Stack<String> history = new Stack<>();
String word = null;

while (!word.equals(exit)) {

   word = scan.nextLine();

   if (word.equals(show)) {
   
      showHistory();
   } else {
   
     history.push(word);
   }
}

And showHistory(); function have this format:

for (String i : history) {
    System.out.println(i);
}

The issue is, when I execute this, the output I get it's the words the user might have introduced but in a FIFO format. For example, if the user introduces:

Pencil

Book

Shirt

The output this program shows is:

Pencil

Book

Shirt

But the output I want, following the LIFO format is:

Shirt

Book

Pencil

I also don't want to delete the data the stack is storing in any point of the execution, so I don't want to use history.pop(); because, if I'm not wrong, that would delete the data in the stack.

How can I do this?

Thanks in advance.


Solution

  • For this you yould create a helper stack which can hold the popped items temporarily:

    Stack<String> temp = new Stack<>();
    while(!history.isEmpty()){
        System.out.println(history.peek());
        temp.push(history.pop);
    }
    while(!temp.isEmtpy){
        history.push(temp.pop);
    }