题解 | #设计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());
            }
        }
    }
}

全部评论

相关推荐

04-11 21:31
四川大学 Java
野猪不是猪🐗:(ja)va学弟这招太狠了
点赞 评论 收藏
分享
04-22 15:13
已编辑
Java
点赞 评论 收藏
分享
想申请延毕了,找工作找到崩溃,越找就越想摆烂,还有25届的和我一样感受吗?
码农索隆:没事哒,好兄弟,慢慢来,调整心态,车到山前必有路,感到迷茫的时候,多抬头看看
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务