题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
import java.util.Stack;
public class Solution {
private static Stack<Integer> stack = new Stack<>();
private static Stack<Integer> stack_Min = new Stack<>();
public void push(int node) {
stack.push(node);
try{
if(node < stack_Min.peek()){
stack_Min.push(node);
}else{
stack_Min.push(stack_Min.peek());
}
}catch(Exception e){
stack_Min.push(node);
}
}
public void pop() {
stack.pop();
stack_Min.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return stack_Min.peek();
}
}
本文介绍了一种在栈结构中实现获取最小元素功能的方法,通过维护两个栈来实现实现。此方法适用于需要频繁操作栈并快速获取最小元素的场景。
240

被折叠的 条评论
为什么被折叠?



