当前位置:网站首页>leetcode:232. 用栈实现队列【双栈,一个辅助一个模拟队列】
leetcode:232. 用栈实现队列【双栈,一个辅助一个模拟队列】
2022-06-29 15:37:00 【白速龙王的回眸】

分析
st1保持栈顶就是对顶,这样的话需要倒转两次
也就是st1每次接受一个新的x
先全部倒进去st2,然后st2再append x
最后再把st2全部倒入st1
ac code
class MyQueue:
def __init__(self):
self.st1 = [] # 从栈顶到栈底就是队列头到队列尾
self.st2 = [] # 辅助栈
def push(self, x: int) -> None:
if not self.st1:
self.st1.append(x)
else:
# 把st1倒过来
while self.st1:
self.st2.append(self.st1.pop())
self.st2.append(x) # 补到最后
# 再次回到st1,变成queue
while self.st2:
self.st1.append(self.st2.pop())
#print(len(self.st1))
def pop(self) -> int:
#print(len(self.st1))
return self.st1.pop()
def peek(self) -> int:
return self.st1[-1]
def empty(self) -> bool:
return len(self.st1) == 0
# 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()
总结
双栈实现队列
边栏推荐
- Business Intelligence BI and business management decision-making thinking No. 3: business quality analysis
- 有望显著提高集成光子电路的计算性能,清华团队提出了一种衍射图神经网络框架
- swoole TCP 分布式实现
- C # learning 1: value type and reference type
- taro3.*中使用 dva 入门级别的哦
- 微信公告号 图灵机器人实现智能回复
- Numpy 的研究仿制 1
- Volcano engine was selected into the first "panorama of edge computing industry" in China
- Andorid Jetpack Hilt
- 关于 国产麒麟系统运行Qt,在命令行可以运行而双击无法运行(无反应) 的解决方法
猜你喜欢
随机推荐
PostgreSQL source code learning (24) -- transaction log ⑤ - log writing to wal buffer
kotlin 注解声明与使用
Aleph Farms聘请监管事务主管,提前为全球商业化做好准备
Paging SQL (rownum, row_number, deny_rank, rank)
three.js和高德地图结合引入obj格式模型-效果演示
A. Print a Pedestal (Codeforces logo?)
京东联盟API - 万能转链接口 - 京品库接口 - 接口定制
What are the advantages of intelligent chat robots? Senior independent station sellers tell you!
Motion capture system for apple picking robot
企业转型升级之道:数字化转型,思想先行
2022-06-29日报: 李飞飞划重点的「具身智能」,走到哪一步了?
Flink SQL task taskmanager memory settings
瓜分1000+万奖金池,昇腾AI创新大赛2022实力赋能开发者
wallys/m.2/Adapter card(one pcie1x to 4 x Mini PCIE)
LeetCode-470-用Rand7()实现Rand10()
89.(cesium篇)cesium聚合图(自定义图片)
LeetCode-64-最小路径和
无意发现的【TiDB缓存表】,竟能解决读写热点问题
Leetcode-64- minimum path sum
绑定证券账户到同花顺安全吗?哪家券商开户后可以绑定同花顺









