/** Initialize your data structure here. */ publicMyQueue() { pushStack = newStack<>(); popStack = newStack<>(); } /** Push element x to the back of queue. */ publicvoidpush(int x) { stackTransfer(popStack, pushStack); pushStack.push(x); } /** Removes the element from in front of queue and returns that element. */ publicintpop() { stackTransfer(pushStack, popStack); if (popStack.isEmpty()) thrownewRuntimeException("Queue is empty"); return popStack.pop(); } /** Get the front element. */ publicintpeek() { stackTransfer(pushStack, popStack); if (popStack.isEmpty()) thrownewRuntimeException("Queue is empty"); return popStack.peek(); } /** Returns whether the queue is empty. */ publicbooleanempty() { return pushStack.isEmpty() && popStack.isEmpty(); }
/** Put elements from stack1 into stack2. */ publicvoidstackTransfer(Stack stack1, Stack stack2) { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } } }
def__init__(self): """ Initialize your data structure here. """ self.push_stack = [] self.pop_stack = []
defpush(self, x): """ Push element x to the back of queue. """ self.stack_transfer(self.pop_stack, self.push_stack) self.push_stack.append(x)
defpop(self): """ Removes the element from in front of queue and returns that element. """ self.stack_transfer(self.push_stack, self.pop_stack) iflen(self.pop_stack) == 0: returnNone return self.pop_stack.pop()
defpeek(self): """ Get the front element. """ self.stack_transfer(self.push_stack, self.pop_stack) iflen(self.pop_stack) == 0: returnNone return self.pop_stack[-1]
defempty(self): """ Returns whether the queue is empty. """ returnlen(self.push_stack) == 0andlen(self.pop_stack) == 0
defstack_transfer(self, stack1, stack2): """ Put elements from stack1 into stack2. """ iflen(stack2) == 0: whilelen(stack1) != 0: stack2.append(stack1.pop())