题解 | #包含min函数的栈#
包含min函数的栈
http://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
# write code here
if self.stack2 == []:
self.stack2.append(node)
else:
if node < self.stack2[-1]:
self.stack2.append(node)
else:
self.stack2.append(self.stack2[-1])
# stack2的长度要和stack1保持一致,因为有可能stack1栈顶就是最小值
# 所以每当stack1进行出栈操作,stack2也要同步进行出栈
self.stack1.append(node)
def pop(self):
# write code here
self.stack2.pop()
return self.stack1.pop()
def top(self):
# write code here
return self.stack1[-1]
def min(self):
# write code here
return self.stack2[-1]