题解 | #包含min函数的栈#

包含min函数的栈

https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49

import java.util.Stack;

public class Solution {

    private Stack<Integer> stack1 = new Stack<>();
    private Stack<Integer> stack2 = new Stack<>();

    
    public void push(int node) {
        if (stack1.isEmpty()) {
            stack1.push(node);
            stack2.push(node);
        } else {
            int val = stack2.peek();
            if (val < node) {
                stack2.push(val);
            } else {
                stack2.push(node);
            }
            stack1.push(node);
        }
    }
    
    public void pop() {
        if (stack1.isEmpty()) {
            throw new RuntimeException("The stack is empty");
        }
        stack1.pop();
        stack2.pop();
    }
    
    public int top() {
        if (stack1.isEmpty()) {
            throw new RuntimeException("The stack is empty");
        }
        return stack1.peek();
    }
    
    public int min() {
        if (stack2.isEmpty()) {
            throw new RuntimeException("The stack is empty");
        }
        return stack2.peek();
    }
}

全部评论

相关推荐

野猪不是猪🐗:还是太卑微了,什么叫放弃本次面试应该说经过评估,贵公司与自己不匹配,决定不再推进后续流程
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务