题解 | #设计getMin功能的栈#
设计getMin功能的栈
https://www.nowcoder.com/practice/05e57ce2cd8e4a1eae8c3b0a7e9886be
import java.util.Scanner; import java.util.Stack; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); Stack<Integer> stackData = new Stack<>(); Stack<Integer> stackMin = new Stack<>(); for(int i = 0; i < n; i++) { String line = in.nextLine(); String[] buff = line.split(" "); if("push".equals(buff[0])) { stackData.push(Integer.parseInt(buff[1])); if(stackMin.isEmpty()) { stackMin.push(Integer.parseInt(buff[1])); }else if(stackMin.peek() < Integer.parseInt(buff[1])) { stackMin.push(stackMin.peek()); }else { stackMin.push(Integer.parseInt(buff[1])); } }else if("pop".equals(buff[0])) { stackMin.pop(); stackData.pop(); }else { System.out.println(stackMin.peek()); } } } }