最小元素的min函數

題目描述
定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素的min函數(時間複雜度應爲O(1))。
注意:保證測試中不會當棧爲空的時候,對棧調用pop()或者min()或者top()方法。

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.s_stack = []
        self.min_stack = []
    def push(self, node):
        self.s_stack.append(node)
        if self.min_stack:
            if self.min_stack[-1] > node:
                self.min_stack.append(node)
            else:
                self.min_stack.append(self.min_stack[-1])
        else:
            self.min_stack.append(node)
        # write code here
    def pop(self):
        # write code here
        if self.s_stack: 
            self.s_stack.pop()
            self.min_stack.pop()
    def top(self):
        # write code here
        if self.s_stack: 
                return self.s_stack[-1]
        if self.min_stack:
                return self.min_stack[-1]
    def min(self):
        # write code here
         if self.min_stack:
                return self.min_stack[-1]
         return None
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章