classMyQueue:def__init__(self):
self.stack1 = []
self.stack2 = []
defpush(self, element):# write your code here
self.stack1.append(element)
deftop(self):# write your code here# return the top elementwhile len(self.stack1) != 0:
tmp = self.stack1.pop()
self.stack2.append(tmp)
ans = self.stack2[-1]
while len(self.stack2) != 0:
tmp = self.stack2.pop()
self.stack1.append(tmp)
return ans
defpop(self):# write your code here# pop and return the top elementwhile len(self.stack1) != 0:
tmp = self.stack1.pop()
self.stack2.append(tmp)
ans = self.stack2.pop()
while len(self.stack2) != 0:
tmp = self.stack2.pop()
self.stack1.append(tmp)
return ans
Java
publicclass Queue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
publicQueue() {
// do initialization if necessary
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
publicvoidpush(int element) {
// write your code here
stack1.push(element);
}
publicintpop() {
// write your code herewhile(!stack1.empty()){
int tmp = stack1.pop();
stack2.push(tmp);
}
int ans = stack2.pop();
while(!stack2.empty()){
int tmp = stack2.pop();
stack1.push(tmp);
}
return ans;
}
publicinttop() {
// write your code herewhile(!stack1.empty()){
int tmp = stack1.pop();
stack2.push(tmp);
}
int ans = stack2.peek();
while(!stack2.empty()){
int tmp = stack2.pop();
stack1.push(tmp);
}
return ans;
}
}