Implement Stack by Two Queues 494
Question
Implement the following operations of a stack using queues.
• push(x) -- Push element x onto stack.
• pop() -- Removes the element on top of the stack.
• top() -- Get the top element.
• empty() -- Return whether the stack is empty.
Notes:
• You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
• Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue -- which means only push to back, pop from front, size, and is empty operations are valid.
Solution
水题。同Implement queue by two stacks。
代码如下:
class Stack{
private Queue<Integer> queue1;
private Queue<Integer> queue2;
public Stack(){
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
public void push(int value){
queue1.offer(value);
}
public int pop(){
while(queue1.size() != 1){
queue2.offer(queue1.poll());
}
int res = queue1.poll();
while(!queue2.isEmpty()){
queue1.offer(queue2.poll());
}
return res;
}
public int top(){
while(queue1.size() != 1){
queue2.offer(queue1.poll());
}
int res = queue1.poll();
queue2.offer(res);
while(!queue2.isEmpty()){
queue1.offer(queue2.poll());
}
return res;
}
public boolean isEmpty(){
return queue1.isEmpty();
}
}