剑指offer面试题【30】----包含min函数的栈【Python】【栈】

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

代码实现

class Solution:
    def __init__(self):
        self.stack=[]
        self.minstack=[]
    def push(self, node):
        # write code here
        self.stack.append(node)
        #if not self.minstack or self.minstack[-1]>=node:
        if self.minstack==[] or self.minstack[-1]>=node:#在python中优先级not>>and>>or,if not self.minstack为真表示minstack为空,等价于minstack=[]
            self.minstack.append(node)
        else:
            self.minstack.append(self.minstack[-1])
    def pop(self):
        # write code here
        
        self.stack.pop()
        
        self.minstack.pop()
    def top(self):
        # write code here
        return self.stack[0]
    def min(self):
        # write code here
        return self.minstack[-1]

#测试
p=Solution()
p.push(3)
p.push(4)
p.push(2)
p.push(1)
print(p.top())
print(p.min())
p.pop()
p.pop()
print(p.min())
p.push(0)
print(p.min())

测试结果

猜你喜欢

转载自blog.csdn.net/weixin_42702666/article/details/89951683
今日推荐