题解 | #包含min函数的栈#
包含min函数的栈
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
import java.util.Stack; public class Solution { Stack<Integer> stack = new Stack<>(); int min = Integer.MAX_VALUE; public void push(int node) { stack.push(node); if (min > node) min = node; } public void pop() { int temp = stack.pop(); if (temp == min) { int size = stack.size(); min = Integer.MAX_VALUE; for (Integer integer : stack) min = min > integer ? integer : min; } } public int top() { return stack.peek(); } public int min() { return min == Integer.MAX_VALUE ? 0 : min; } private void receiveStr(String str) { // 按照 , 分割 String[] split = str.split(","); for (String s : split) { // 截取前三个字母 String sub = s.substring(0, 3); String num = s.substring(3); switch (sub) { case "PSH": this.push(Integer.parseInt(num)); break; case "TOP": System.out.println(this.top()); break; case "MIN": System.out.println(this.min()); break; case "POP": this.pop(); break; default: break; } } } }