Java code for reversing a queue ________________________________________________
ID: 3570221 • Letter: J
Question
Java code for reversing a queue
_______________________________________________________________
3. Stacks and Queues.
Assume implementations Stack and Queue exist for the StackInterface and QueueInterfaces below respectively. Complete the instance method reverse() in the Queue class to reverse the order of the elements in that Queue instance.
public interface Queue {
public void enter(Object o);
public Object remove();
public boolean isEmpty();
public void reverse(); // you will implement this method
} // Queue abstraction
public interface Stack {
public void push(Object o);
public Object pop();
public boolean isEmpty();
} // Stack abstraction
public void reverse() { // complete this Queue class instance method as described above
Explanation / Answer
public void reverseQueue(Queue q) { ArrayList list = new ArrayList(); while (! q.isEmpty()) { list.add(q.dequeue()); } for(int k=list.size()-1; k >= 0; k--) { q.enqueue(list.get(k)); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.