题解 | #设计getMin功能的栈#

设计getMin功能的栈

https://www.nowcoder.com/practice/05e57ce2cd8e4a1eae8c3b0a7e9886be

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {

        //正常保存数字的栈
        Stack<Long> stackNum = new Stack<>();
        //保存最小值的栈
        Stack<Long> stackMIn = new Stack<>();

        Scanner in = new Scanner(System.in);

        int N = in.nextInt();

        for (int i = 0; i < N; i++) {
            String str = in.next();

            if (str.startsWith("push")) {
                long num = in.nextInt();
                stackNum.push(num);
                //最小栈入栈的时机
                if (stackMIn.isEmpty() || num <= stackMIn.peek()) {
                    stackMIn.push(num);
                }
            } else if (str.startsWith("pop")) {
                long popNum = stackNum.pop();
                //最小栈弹出的时机
                if (popNum == stackMIn.peek()) {
                    stackMIn.pop();
                }
            } else if (str.startsWith("getMin")) {
                System.out.println(stackMIn.peek());
            }
        }

    }
}

栈和队列,记录栈和队列的一些题

全部评论

相关推荐

02-05 08:18
四川大学 Java
在思考的熊熊很讨厌吃香菜:不是,我门头沟学院呢?这都没排上?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务