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