题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

思路:
考察栈的使用。代码中用到两个栈:
a. 用栈 stack 记录所有元素的值
b. 用辅助栈 min_stack 始终记录每次压栈时的最小元素,min_stack的栈顶就是当前的最小元素

具体操作如下:

  • 假设我们要把数据A入栈,
  • 如果A小于等于 min_stack 的栈顶元素,则同时向stack和min_stack压入A
  • 否则,向min_stack压入min_stack的栈顶元素,向stack压入A
  • 出栈时,stack和min_stack同时出栈

java 代码如下:

import java.util.Stack;

public class Solution

Stack<Integer> stack = new Stack();
Stack<Integer> min_stack = new Stack();

public void push(int node) {


if(min_stack.isEmpty() || node <= min_stack.peek()) {
min_stack.push(node);
}else {
min_stack.push(min_stack.peek());
}
stack.push(node);
}

public void pop() {
min_stack.pop();
stack.pop();
}

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

public int min() {
return

python 代码如下:

# -*- coding:utf-8 -*-

class Solution:
stack = []
min_stack = []

def push(self, node):
if len(self.stack) == 0 or node <= self.stack[-1]:
self.min_stack.append(node)
else:
self.min_stack.append(self.min())
self.stack.append(node)

def pop(self):
self.min_stack.pop()
self.stack.pop()

def top(self):
return self.stack[-1]

def min(self):
return self.min_stack[-1]