用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
#剑指 Offer 09 题目解析
#进栈:stack.append(1) 出栈:stack.pop() 先进后出
#进队:queue.append(1) 出队:queue.popleft() 先进先出 from collections import deque
class CQueue:
def __init__(self):
self.A = []
self.B = []
def appendTail(self, value) -> None:
self.A.append(value)
def deleteHead(self) -> int:
if self.B:
return self.B.pop()
if not self.A:
return -1
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("one")
obj.appendTail("two")
obj.appendTail("three")
print("处理前:")
print("obj.A=",str(obj.A))
param_2 = obj.deleteHead()
print("处理后:")
print("obj.A=",str(obj.A))
print("obj.B=",str(obj.B))