private Stack<Integer> input = null; private Stack<Integer> output = null; /** Initialize your data structure here. */ publicMyQueue(){ input = new Stack<>(); output = new Stack<>(); } /** Push element x to the back of queue. */ publicvoidpush(int x){ input.push(x); } /** Removes the element from in front of queue and returns that element. */ publicintpop(){ if(output.isEmpty()) { while(!input.isEmpty()) { output.push(input.pop()); } } return output.pop(); } /** Get the front element. */ publicintpeek(){ if(output.isEmpty()) { while(!input.isEmpty()) { output.push(input.pop()); } } return output.peek(); } /** Returns whether the queue is empty. */ publicbooleanempty(){ return input.isEmpty() && output.isEmpty(); } }
def__init__(self): """ Initialize your data structure here. """ self.instack = [] self.outstack = []
defpush(self, x): """ Push element x to the back of queue. :type x: int :rtype: void """ self.instack.append(x)
defpop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ ifnot self.outstack: while self.instack: self.outstack.append(self.instack.pop()) return self.outstack.pop()
defpeek(self): """ Get the front element. :rtype: int """ ifnot self.outstack: while self.instack: self.outstack.append(self.instack.pop()) return self.outstack[-1]
defempty(self): """ Returns whether the queue is empty. :rtype: bool """ returnnot self.outstack andnot self.instack