【问题标题】:How to print a stack in Java如何在 Java 中打印堆栈
【发布时间】:2014-11-05 02:54:13
【问题描述】:

我写了一个方法,接收一个队列作为参数,然后把这个队列转换成一个栈。现在我想尝试在 main 中打印这个方法,看看它是否有效,但是没有任何用于堆栈的 toString 方法。

我已经做了一些研究并尝试将堆栈转换为数组,但我无法让它工作。 Printing the stack values in Java

我该怎么做?

public static void QueueStack(Queue<Integer> q){
    Stack<Integer> stack1 = new Stack<Integer>();
    while(!q.isEmpty()){
        int temp = q.dequeue();
        stack1.push(temp);
    }
    Arrays.toString(stack1.toArray());
}

【问题讨论】:

  • 你为什么不想使用 System.out.println(stack1) ?
  • @BatScream 我以为我不能将 Syso 用于堆栈(我使用数组学习堆栈并且必须编写一个 for 来打印值),现在我知道我可以用它来打印它们。
  • 用户 stack1.addAll(q) 而不是循环队列

标签: java stack queue


【解决方案1】:

您是否尝试过使用 Stack 类的 toString() 方法?

例如

stack1.toString();

或者是否有您想要打印的特定格式?

【讨论】:

    【解决方案2】:

    您可以尝试Vector 扩展的Vector 类的get(int index) 方法,假设您不想在打印时从堆栈中弹出元素。

    【讨论】:

      【解决方案3】:
      if (!tack1.isEmpty()) {
          for(Object a : stack1) {
              System.out.println(a);
          }
      }
      

      【讨论】:

        【解决方案4】:

        这里是将给定队列转换为堆栈的方法:

        public static void QueueStack(Queue<Integer> queue){
        
            Stack<Integer> stack = new Stack<>();
            for(Integer in: queue){
                stack.push(in);
            }
            //Here, the output would be same as you inserted elements.As stack uses iterator which prints elements as they are inserted(a bug in stack iteration)
            System.out.println("Stack: "+stack);
            
            //You can use java 8 for-each style as well.
            stack.forEach(System.out::println);
            
            //If you want to traverse stack in LIFO manner..
            while(stack.isEmpty){
            System.ou.println(stack.pop());
            }
            
            //For better performance ArrayDeque<>() is preferred!
            Deque<Integer> stack = new ArrayDeque<Integer>();
            
        }
        

        【讨论】:

          【解决方案5】:

          你也可以非常类似于如何初始化它。

          while(!stack1.isEmpty())
          {
             int t = stack1.pop();
             System.out.println(t);
          }
          

          【讨论】:

            猜你喜欢
            • 2012-08-23
            • 1970-01-01
            • 1970-01-01
            • 2015-08-25
            • 2020-07-06
            • 2016-04-11
            • 1970-01-01
            • 2012-09-04
            • 2020-08-28
            相关资源
            最近更新 更多