09. LeetCode face questions queue wins the Offer [] [] [Easy Python stack] [] [] with two stacks queue
problem
A queue is implemented with two stacks. The following statement queue, implement its two functions appendTail and deleteHead, were completed at the end of the queue insert and delete integer integer in the head of the queue function. (If there is no queue element, deleteHead operation returns -1)
Example 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
Example 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
prompt:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
Thinking
Stack queue
栈:先进后出
队列:先进先出
加入队尾:直接进栈 A
删除队首:主要是实现栈 A 的倒序
Python3 Code
class CQueue:
def __init__(self):
self.A, self.B = [], []
def appendTail(self, value: int) -> None:
self.A.append(value)
def deleteHead(self) -> int:
# B中还有倒序的元素,直接弹出
if self.B:
return self.B.pop()
# A已空
if not self.A:
return -1
# A中元素全部转到B中,实现倒序
while self.A:
self.B.append(self.A.pop())
return self.B.pop()
# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()