如何在Java中打印堆栈

如何在Java中打印堆栈,java,stack,queue,Java,Stack,Queue,我编写了一个方法,该方法接收队列作为参数,然后将该队列转换为堆栈。现在我想主要打印这个方法,看看它是否有效,但是没有任何用于堆栈的toString方法 我已经做了一些研究,并试图将堆栈转换为数组,但我无法让它工作 我该怎么做 public static void QueueStack(Queue<Integer> q){ Stack<Integer> stack1 = new Stack<Integer>(); while(!q.isEmpty

我编写了一个方法,该方法接收队列作为参数,然后将该队列转换为堆栈。现在我想主要打印这个方法,看看它是否有效,但是没有任何用于堆栈的toString方法

我已经做了一些研究,并试图将堆栈转换为数组,但我无法让它工作

我该怎么做

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());
}
publicstaticvoidqueuestack(队列q){
Stack stack1=新堆栈();
而(!q.isEmpty()){
int temp=q.dequeue();
堆栈1.推送(温度);
}
toString(stack1.toArray());
}

是否尝试使用堆栈类的toString()方法

e、 g


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

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

您也可以执行与初始化元素非常类似的操作

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

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

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>();
    
}
publicstaticvoidqueuestack(队列队列){
堆栈=新堆栈();
for(队列中的整数){
堆叠。推(入);
}
//在这里,输出将与插入的元素相同
System.out.println(“Stack:+Stack”);
//您也可以对每种样式使用Java8。
stack.forEach(System.out::println);
//若你们想以后进先出的方式遍历堆栈。。
while(stack.isEmpty){
System.ou.println(stack.pop());
}
//为了获得更好的性能,首选ArrayDesk()!
Deque stack=new ArrayDeque();
}

你为什么不想使用System.out.println(stack1)?可能重复@Batshray?我以为我不能使用Syso进行堆栈(我学习了使用数组的堆栈,必须编写一个for来打印值),现在我知道我可以使用它来打印它们。用户stack1.addAll(q)而不是循环队列
if (!tack1.isEmpty()) {
    for(Object a : stack1) {
        System.out.println(a);
    }
}
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>();
    
}