包含min函数的栈(python)

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
# -*- coding:utf-8 -*-
class Solution:
       #入栈时,若新值比最小值栈的栈顶还小,则将该值同时push到最小值栈;
       #出栈时,若现有栈的栈顶和最小值栈栈顶一致,则同时出栈,否则,
       #仅仅现有栈pop;通过这一操作,最小值栈的栈顶将永远是现有栈元素中的最下值。
    def push(self, node):
        # write code here
        self.stack.append(node)
    def pop(self):
        # write code here
        if self.stack != []:
            self.stack.pop(-1)
    def top(self):
        # write code here
        if self.stack != []:
            return self.stack[-1]
        else:
            return None
    def min(self):
        # write code here
        return min(self.stack)
    def __init__(self):
        self.stack = []

  

原文地址:https://www.cnblogs.com/277223178dudu/p/10447606.html