Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在不删除Java中的内容的情况下显示后进先出堆栈的内容?_Java_Stack_Lifo - Fatal编程技术网

如何在不删除Java中的内容的情况下显示后进先出堆栈的内容?

如何在不删除Java中的内容的情况下显示后进先出堆栈的内容?,java,stack,lifo,Java,Stack,Lifo,我正试图创建一种“历史”特性,它遵循后进先出的特点。最后输入第一输出 因此,用户将引入一些单词,这些单词将存储在堆栈中,以便在单词之后打印它们。总结的程序如下所示: Stack<String> history = new Stack<>(); String word = null; while (!word.equals(exit)) { word = scan.nextLine(); if (word.equals(show)) {

我正试图创建一种“历史”特性,它遵循后进先出的特点。最后输入第一输出

因此,用户将引入一些单词,这些单词将存储在堆栈中,以便在单词之后打印它们。总结的程序如下所示:

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

while (!word.equals(exit)) {

   word = scan.nextLine();

   if (word.equals(show)) {
   
      showHistory();
   } else {
   
     history.push(word);
   }
}
问题是,当我执行此操作时,我得到的输出是用户可能引入的单词,但采用FIFO格式。例如,如果用户介绍:

铅笔

衬衫

该程序显示的输出为:

铅笔

衬衫

但是我想要的输出,按照后进先出格式是:

衬衫

铅笔

我也不想删除堆栈存储在任何执行点的数据,所以我不想使用
history.pop()
我该怎么做


提前感谢。

为此,您需要创建一个帮助器堆栈,可以临时保存弹出的项目:

Stack temp=new Stack();
而(!history.isEmpty()){
System.out.println(history.peek());
临时推送(history.pop);
}
而(!温度isEmtpy){
历史推送(临时弹出);
}

如果你想倒序,就这么做吧

for (ListIterator  i = history.listIterator(history.size()); i.hasPrevious();) {
    System.out.println(i.previous());
}

如果您可以自由使用任何Java类,您可以使用Deque而不是堆栈?迭代器()和下降迭代器()方法将完成您的工作

来自堆栈文档:Deque接口及其实现提供了一组更完整、更一致的后进先出堆栈操作,应该优先使用此类

for (ListIterator  i = history.listIterator(history.size()); i.hasPrevious();) {
    System.out.println(i.previous());
}