In: Computer Science
Write a method public static Stack reverse(Stack s) that reverses the order of elements on stack s using a Queue. Test your method using some example stacks. In java
/*If you have any query do comment in the comment section else like the solution*/
import java.util.*;
public class ReverseStack {
public static Stack reverse(Stack s) {
Queue<Integer> q = new LinkedList<Integer>();
while(s.size() > 0) {
q.add((Integer) s.pop());
}
while(q.size() > 0) {
s.push(q.poll());
}
return s;
}
public static void main(String[]args) {
Stack<Integer> s = new Stack();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
System.out.println("Original Stack : " + s);
System.out.println("Reversed Stack: " + reverse(s));
}
}
Output: