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 must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, andis empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue byusing a list or deque (double-ended queue), aslongas you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
import java.util.LinkedList;
import java.util.Queue;
class MyStack {
Queue<Integer> pre = new LinkedList<Integer>();
Queue<Integer> next = new LinkedList<Integer>();
// Push element x onto stack.publicvoidpush(int x) {
if(next != null){
next.add(x);
}else{
pre.add(x);
}
}
// Removes the element on top of the stack.publicvoidpop() {
if(!next.isEmpty()){
while(!next.isEmpty()){
int a = next.poll();
if(!next.isEmpty()){
pre.add(a);
}
}
}else{
while(!pre.isEmpty()){
int b = pre.poll();
if(!pre.isEmpty()){
next.add(b);
}
}
}
}
// Get the top element.publicinttop() {
if(!next.isEmpty()){
while(!next.isEmpty()){
int c = next.poll();
pre.add(c);
if(next.isEmpty()){
return c;
}
}
}else{
while(!pre.isEmpty()){
int d = pre.poll();
next.add(d);
if(pre.isEmpty()){
return d;
}
}
}
return0;
}
publicbooleanempty() {
if(next.isEmpty() && pre.isEmpty()){
returntrue;
}else{
returnfalse;
}
}
}