FollowMee 发表于9个月前

• 发表于 9个月前
• 阅读 0
• 收藏 0
• 评论 0

# 包含min函数的栈

• 常规写法
``````# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.s1 = []
self.s2 = []

def push(self, node):
# write code here
if not self.s1 and not self.s2: #栈空间为空时插入
self.s1.append(node)
self.s2.append(node)
else:
self.s1.append(node)
if node < self.s2[-1]: #插入值小于最小栈顶点值时
self.s2.append(node)
else:
self.s2.append(self.s2[-1]) #插入值大于最小栈顶点值时
def pop(self):
# write code here
if self.s1 and self.s2:
self.s2.pop()
return self.s1.pop()
return None
def top(self):
# write code here
if self.s1:
return self.s1[-1]
return None
def min(self):
# write code here
if self.s2:
return self.s2[-1]
return None``````

• Pythonic

``````# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.s = []
def push(self, node):
# write code here
self.s.append(node)
def pop(self):
# write code here
if self.s:
return self.s.pop()
return None
def top(self):
# write code here
if self.s:
return self.s[-1]
return None
def min(self):
# write code here
if self.s:
return min(self.s)
return None``````

×