class Stack:
def __init__(self):
self.items = []
def empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def peek(self):
if not self.empty():
return self.items[len(self.items) - 1]
else:
return None
def pop(self):
if not self.empty():
return self.items.pop()
else:
print('栈已经为空')
def push(self, x):
self.items.append(x)
class MyStack:
def __init__(self):
self.elemStack = Stack() # 用来存储栈中的元素
self.minStack = Stack() # 栈顶永远存储当前elemStack中最小的值
def push(self, data):
self.elemStack.push(data)
if self.minStack.empty():
self.minStack.push(data)
elif data < self.minStack.peek():
self.minStack.push(data)
def pop(self):
topData = self.elemStack.peek()
self.elemStack.pop()
if topData == self.mins():
self.minStack.pop()
return topData
def mins(self):
if self.minStack.empty():
return 2 ** 32
else:
return self.minStack.peek()
if __name__ == '__main__':
stack = MyStack()
stack.push(5)
print('栈中最小值为:' + str(stack.mins()))
stack.push(6)
print('栈中最小值为:' + str(stack.mins()))
stack.push(2)
print('栈中最小值为:' + str(stack.mins()))
stack.pop()
print('栈中最小值为:' + str(stack.mins()))
运行结果如下:
栈中最小值为:5
栈中最小值为:5
栈中最小值为:2
栈中最小值为:5