题解 | #包含min函数的栈#
包含min函数的栈
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=295&tqId=23268&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
# -*- coding:utf-8 -*- class Solution: stack = [] stack_min = [] def push(self, node): # write code here # print(node) #普通栈栈顶入栈 self.stack.append(node) if not self.stack_min: # 添加最小栈栈顶元素 self.stack_min.append(node) else: # 最小栈栈顶元素更新 if node <= self.stack_min[-1]: self.stack_min.append(node) def pop(self): # write code here length = len(self.stack) length2 = len(self.stack_min) # 更新栈顶元素 x = self.stack[-1] self.stack = self.stack[: length - 1] # 最小栈栈顶元素出栈 if x == self.stack_min[-1]: self.stack_min = self.stack_min[: length2 - 1] return x def top(self): # write code here x = self.stack[-1] return x def min(self): # write code here return self.stack_min[-1]