# 一周刷完剑指offer-20-包含min函数的栈

## 3. 解题思路

``````栈  3，4，2，5，1

``````

## 4. Java实现

``````import java.util.Stack;

public class Solution {

private Stack dataStack = new Stack();
private Stack minStack = new Stack();

public void push(int node) {
dataStack.push(node);
if (minStack.isEmpty() || min() > node){ // 如果为空，则之间push进去，如果最小栈的最小值都比node大，也把node值push
minStack.push(node);
}else{
minStack.push(min());
}
}

public void pop() {
dataStack.pop();
minStack.pop();
}

public int top() {
return dataStack.peek();
}

public int min() {
return minStack.peek();
}
}``````

## 5. Python实现

``````# -*- coding:utf-8 -*-
class Solution:
def __init__(self): #使用两个栈来实现，两个栈的大小是相同的
self.stack = []
self.minStack = []

def push(self, node):
# write code here
self.stack.append(node)
if not self.minStack or self.min() > node: # 将最小值增加到minStack中
self.minStack.append(node)
else:
self.minStack.append(self.min())

def pop(self):
# write code here
if self.stack and self.minStack:
self.stack.pop()
self.minStack.pop()
else:
return None

def top(self):
# write code here
return self.stack[-1]
def min(self):
# write code here
return self.minStack[-1]``````