Python implements a stack containing min functions and pythonmin Functions
This example describes how to implement a Python stack that contains min functions. We will share this with you for your reference. The details are as follows:
# Coding = utf8''' question: defines the data structure of the stack. Implement a min function in this type to obtain the minimum element of the stack. In this stack, the time complexity of calling min, push, and pop is O (1 ). '''Class Stack (): def _ init _ (self): self. main_stack = [] # secondary stack. Each time the smallest element is pushed into the secondary stack self. performance_stack = [] # record the minimum element self in the stack. _ min = None def min (self): return self. _ min def push (self, data): self. main_stack.append (data) if self. _ min is None: self. _ min = data else: if data <self. _ min: self. _ min = data # push the smallest element into the auxiliary stack self. performance_stack.append (self. _ min) def pop (self): if len (self. main_stack) = 0: raise Exception ('no data') elif len (self. main_stack) = 1: self. performance_stack.pop () self. _ min = None return self. main_stack.pop () else: self. performance_stack.pop () self. _ min = self. performance_stack [-1] return self. main_stack.pop () if _ name _ = '_ main _': s = Stack () s. push (3) s. push (4) s. push (2) s. push (1) print s. min () s. pop () s. pop () print s. min () s. pop () print s. min () s. pop () print s. min () s. pop ()