【问题标题】:How to show the contents of each stack from top to bottom?如何从上到下显示每个堆栈的内容?
【发布时间】:2021-02-06 06:43:34
【问题描述】:

我想在下面的代码执行后输出每个堆栈的内容。到目前为止它的输出为

Stack@568db2f2
Stack@378bf509
Stack@378bf509

但我想要每个堆栈的内容。

代码:

public static void main(String[] args) {
    Stack<Integer> a = new Stack<>();
    Stack<Integer> b = new Stack<>();
    Stack<Integer> c = new Stack<>();

    a.push(28);
    b.push(a.pop());
    b.peek();
    c.push(21);
    a.push(14);
    a.peek();
    b.push(c.pop());
    c.push(7);
    b.push(a.pop());
    b.push(c.pop());

    System.out.println(a);
    System.out.println(b);
    System.out.println(b);

}

【问题讨论】:

  • 如果您不需要在程序结束时仍然填充堆栈,您可以 pop 一次一个元素(直到堆栈为空)并打印它。
  • 您期望每个堆栈内容的输出类型是什么? String [28, 21, 14, 7] ?
  • @aKilleR 他们最终会是空的吗?
  • @EGS99 ,如果使用peek()不会为空检查This out

标签: java stack


【解决方案1】:

似乎Stack 类的默认toString() 打印堆栈在内存中的位置或类似的东西,而不是打印堆栈的内容。您应该为每个堆栈使用以下代码(stk 是您要打印其内容的原始堆栈):

//Create another temporary Stack
Stack<Integer> temp = new Stack<>();

//Print each content of the original Stack (stk) separately.
//Move each content to the temporary Stack (temp), in order to preserve it.
while(! stk.empty())
   {
       System.out.println(stk.peek());
       temp.push(stk.pop());
   }

//Move all the content back to the original Stack (stk)
while(! temp.empty())
   {
       stk.push(temp.pop());
   }

【讨论】:

    【解决方案2】:

    Stack&lt;E&gt;Vector&lt;E&gt; 的子类,您可以使用.size().elementAt(int index) on:

    Stack<String> stack = new Stack<String>();
    stack.push("!");
    stack.push("world");
    stack.push(" ");
    stack.push("Hello");
    for (int i = stack.size() - 1; i >= 0; --i) {
      System.out.print(i);
    }
    System.out.println();
    

    然而,正如 Federico 指出的那样,如果您在打印堆栈时不关心清空堆栈,那么您也可以循环调用 .pop() 直到它们为空。

    但是,正如this answer 指出的那样,您应该使用Deque&lt;E&gt; 而不是Stack&lt;E&gt;LinkedList&lt;E&gt; 实现了Deque&lt;E&gt;,并且可以轻松地迭代以打印其元素(从上到下):

    Deque<String> stack = new LinkedList<String>();
    stack.push("!");
    stack.push("world");
    stack.push(" ");
    stack.push("Hello");
    for (String item : stack) {
      System.out.print(item);
    }
    System.out.println();
    

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 2023-04-06
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      相关资源
      最近更新 更多