当前位置:网站首页>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()
总结
双栈实现队列
边栏推荐
- European standard plug en50075 test items
- CVPR 2022 | 大幅减少零样本学习所需的人工标注,马普所和北邮提出富含视觉信息的类别语义嵌入
- 《网络是怎么样连接的》读书笔记 - 服务器端的局域网中(四)
- 关于 麒麟系统启动应用报错“undefined symbol: __cxa_throw_bad_array_new_length, version Qt_5“ 的解决方法
- JS will have variable promotion and function promotion
- 如何用好数据科学?
- Taro 小程序开启wxml代码压缩
- C#学习二:堆和栈
- C SQLite class library
- Detailed explanation of list set
猜你喜欢
如何使用SMS向客户传递服务信息?指南在这里!
Flink SQL task taskmanager memory settings
商业智能BI与业务管理决策思维之三:业务质量分析
Andorid Jetpack Hilt
Detailed explanation of list set
Mingdeyang xilinx-k7-325t/410t core board data manual
The way of enterprise transformation and upgrading: digital transformation, thinking first
LeetCode-64-最小路径和
LeetCode-234-回文链表
Imgutil image processing tool class, text extraction, image watermarking
随机推荐
13.TCP-bite
Numpy 的研究仿制 1
从第三次技术革命看企业应用三大开发趋势
C learning 2: heap and stack
kotlin 注解声明与使用
Business Intelligence BI and business management decision-making thinking No. 3: business quality analysis
天谋科技 Timecho 完成近亿元人民币天使轮融资,围绕 Apache IoTDB 打造工业物联网原生时序数据库
List集合详细讲解
Cmake learning-2
Polarimetric SAR surface classification
Kotlin annotation Statement and use
Several imaging modes of polarimetric SAR
Taro2.* 小程序配置分享微信朋友圈
C語言大作業——匹配系統
为Golang项目编写Makefile
14.ip protocol -bite
企业转型升级之道:数字化转型,思想先行
架构实战营模块五作业
商业智能BI与业务管理决策思维之三:业务质量分析
Building SQL statements in Excel