Reputation: 53
public static void reverse(Stack arr){
Queue<Integer> arrCopy=new LinkedList<Integer>();
while(!arr.empty()){
arrCopy.add((int)arr.pop());
};
System.out.print("{ ");
while(!arrCopy.isEmpty()){
System.out.print((int)arrCopy.remove() + ", ");
}
System.out.print("}");
}
so, i have a stack with 10 integers and i'd like to print it in reverse. i wrote a new method that creates a queue, and every time it removes and returns an integer from the stack using pop, it will add it onto the queue. the problem is that while(!arrCopy.isEmpty())
does not seem to be executing and the queue is empty. is there a casting problem here? or is there something wrong with the way i've added elements to the queue?
thanks!
edit: here is the code for my main function (which is the rest of my code):
public static void main(String[] args) {
Random rand = new Random();
Stack<Integer> a=new Stack<Integer>();
for (int i=0; i<10; i++){
a.push(rand.nextInt(50));
}
System.out.print("{ ");
while(!a.empty()){
System.out.print((int)a.pop() + ", ");
}
System.out.print("}");
reverse(a);
}
solution: i got it to work, thank you! the problem was that i was using pop to return (yet remove) all elements from the stack in order to print it before reversing it, which resulted in an empty stack. this is how i changed it to work!
public static Queue reverse(Stack arr){
Queue<Integer> arrCopy=new LinkedList<Integer>();
while(!arr.empty()){
arrCopy.add((int)arr.pop());
}
return arrCopy;
}
public static void main(String[] args) {
Random rand = new Random();
Stack<Integer> a=new Stack<Integer>();
for (int i=0; i<10; i++){
a.push(rand.nextInt(50));
}
System.out.println("List:");
System.out.println(a);
System.out.println("Reversed List:");
System.out.println(reverse(a));
}
Upvotes: 3
Views: 32264
Reputation: 59113
Here:
while(!a.empty()){
System.out.print((int)a.pop() + ", ");
}
System.out.print("}");
reverse(a);
You are emptying the stack before calling reverse
. If you keep popping elements off the stack until a.empty()
returns true, then you have emptied the stack, and you are passing an empty stack to the reverse
method.
Why not just use:
System.out.println(a);
reverse(a);
There's no need to pop all the elements off your stack in order to print them.
Upvotes: 1
Reputation: 3180
Just reverse the stack order using below code. That revers the order.
import java.util.Collections;
import java.util.Stack;
public class Test {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < 10; i++) {
stack.push(i);
}
System.out.println("Before reverse" + stack);
reverse(stack);
}
public static void reverse(Stack<Integer> arr){
arr.sort(Collections.reverseOrder());
System.out.println("After reverse");
System.out.println(arr);
}
}
Out put is:
Before reverse[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After reverse
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Upvotes: 3