0

I wrote a method that receives a queue as a parameter and then convert this queue into a stack. Now I want to try to print this method in the main to see if it works, but there isn't any toString method for stacks.

I already did some research and tried to convert stacks into arrays, but I can't get it to work. Printing the stack values in Java

How can I do this?

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());
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2737948
  • 329
  • 2
  • 10
  • 25

5 Answers5

1

Did you try using the Stack classes' toString() method?

e.g.

stack1.toString();

Or was there a specific format you want to print out?

HedonicHedgehog
  • 592
  • 1
  • 6
  • 17
0

You could try the get(int index) method of the Vector class which Stack extends, assuming you don't want to pop the elements from your stack while you print them.

pez
  • 3,859
  • 12
  • 40
  • 72
0

You could also do it very similar to how to initialized it.

while(!stack1.isEmpty())
{
   int t = stack1.pop();
   System.out.println(t);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0
if (!tack1.isEmpty()) {
    for(Object a : stack1) {
        System.out.println(a);
    }
}
0

Here, is a method to convert a given Queue to Stack:

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>();
    
}