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

全部评论

相关推荐

纯朴的商业竞争手段
职场不咸鱼:看来商家也喜欢jd
投递美团等公司6个岗位 > 京东美团大战,你怎么看?
点赞 评论 收藏
分享
03-16 13:56
湖南大学 C++
牛客872108596号:到现在没消息是挂了吗查看图片
点赞 评论 收藏
分享
03-05 12:52
吉林大学 Java
挣K存W养DOG:他的价值在于把他家里积攒的财富回馈给社会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务