////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////
Queue as Stack
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////
Version A:
push:
enqueue in queue1
pop:
while size of queue1 is bigger than 1, pipe dequeued items from queue1 into queu
e2
dequeue and return the last item of queue1, then switch the names of queue1 and
queue2
Version B:
push:
enqueue in queue2
enqueue all items of queue1 in queue2, then switch the names of queue1 and queue
2
pop:
deqeue from queue1
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////
Stack as Queue
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////
public class Queue<E>
{
private Stack<E> inbox = new Stack<E>();
private Stack<E> outbox = new Stack<E>();
public void queue(E item) {
inbox.push(item);
}
public E dequeue() {
if (outbox.isEmpty()) {
while (!inbox.isEmpty()) {
outbox.push(inbox.pop());
}
}
return outbox.pop();
}
}

Sign up to vote on this title
UsefulNot useful