化栈为队
实现一个MyQueue类,该类用两个栈来实现一个队列
很简单
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.A, self.B = [], []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.A.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if self.B:
return(self.B.pop())
while self.A:
self.B.append(self.A.pop())
return(self.B.pop())
def peek(self) -> int:
"""
Get the front element.
"""
if self.B:
return(self.B[-1])
while self.A:
self.B.append(self.A.pop())
return(self.B[-1])
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
if self.B or self.A:
return(False)
return(True)
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()