Reputation: 175
Ok, so I'm trying to modify a queue to have its content reversed using a stack. I'm a bit lost. I know it shouldn't take much code to write it so I'm hoping someone can help and make this a bit more clear. The inputted queue is random, I'm just using [1,2,3,4] to visualize.
The methods I can use are here:
http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html
http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html
Thanks.
Just from writing this I am getting an error at stack.push(queue)
which is
The method push(java.lang.Integer) in the type java.util.Stack<java.lang.Integer> is not applicable for the arguments (java.util.Queue)
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<Integer>();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
ReverseQueue(q);
}
public static void ReverseQueue(Queue queue) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(queue);
System.out.println(queue);
}
Upvotes: 0
Views: 186
Reputation: 3778
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<Integer>();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
reverseQueue(q);
}
public static void reverseQueue(Queue<Integer> queue) {
Stack<Integer> stack = new Stack<Integer>();
while (!queue.isEmpty()) {
stack.push(queue.remove());
}
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
System.out.println(queue);
}
Upvotes: 1