Implement Stack by Two Queues
LintCode-494.Implement Stack by Two Queues
Implement a stack by two queues. The queue is first in first out (FIFO). That means you can not directly pop the last element in a queue.
For this question, you need to pay attention to the push(int x) method.
class Stack {
Queue<Integer> queue = new LinkedList<Integer>();
// Push a new item into the stack
public void push(int x) {
if (queue.isEmpty()) {
queue.offer(x);
return;
}
Queue<Integer> tempQueue = new LinkedList<Integer>();
while (!queue.isEmpty()) {
tempQueue.offer(queue.poll());
}
queue.offer(x);
while (!tempQueue.isEmpty()) {
queue.offer(tempQueue.poll());
}
}
// Pop the top of the stack
public void pop() {
queue.poll();
}
// Return the top of the stack
public int top() {
return queue.peek();
}
// Check the stack is empty or not.
public boolean isEmpty() {
return queue.isEmpty();
}
}
Hope this helps,
Michael