I have the following homework question:
Implement the stack methods push(x) and pop() using two queues.
This seems odd to me because:
- A Stack is a (LIFO) queue
- I don't see why you would need two queues to implement it
I searched around:
and found a couple solutions. This is what I ended up with:
public class Stack<T> {
LinkedList<T> q1 = new LinkedList<T>();
LinkedList<T> q2 = new LinkedList<T>();
public void push(T t) {
q1.addFirst(t);
}
public T pop() {
if (q1.isEmpty()) {
throw new RuntimeException(
"Can't pop from an empty stack!");
}
while(q1.size() > 1) {
q2.addFirst( q1.removeLast() );
}
T popped = q1.pop();
LinkedList<T> tempQ = q1;
q1 = q2;
q2 = tempQ;
return popped;
}
}
But I don't understand what the advantage is over using a single queue; the two queue version seems pointlessly complicated.
Say we choose for pushes to be the more efficient of the 2 (as I did above), push would remain the same, and pop would simply require iterating to the last element, and returning it. In both cases, the push would be O(1), and the pop would be O(n); but the single queue version would be drastically simpler. It should only require a single for loop.
Am I missing something? Any insight here would be appreciated.