当前位置: 首页 > 工具软件 > Poptop > 使用案例 >

Python之设计一个pop、push、top并能在常数时间内检测最小元素的栈

柴声
2023-12-01

设计一个pop、push、top、getmin操作,并能在常数时间内检测最小元素的栈

class Minstack(object):
    def __init__(self):
        self.stack = []
        self.Minstack = []
    def isEmpty(self):
        return len(self.stack)<1
    def push(self,item):
        self.stack.append(item)
        if self.Minstack == [] or item<self.Minstack[-1]:
            self.Minstack.append(item)
    def top(self):
        if not self.isEmpty():
            return self.stack[-1]
    def getMin(self):
        if not self.isEmpty():
            return self.Minstack[-1]
    def pop(self):
        if not self.isEmpty():
            if self.Minstack[-1]==self.top():
                self.Minstack.pop()
            self.stack.pop()
stack = Minstack()
stack.push(-2)
stack.push(0)
stack.push(-3)
stack.push(5)
stack.push(-4)
print(stack.getMin())
stack.pop()
print(stack.top())
print(stack.getMin())
 类似资料: