20-包含min函数的栈

1. 题目描述

图片说明

2. 题解

----------------------------------------------【2021-08-09】更新---------------------------------------------------------

import java.util.Stack;

public class Solution {
    Stack<Integer> mystack=new Stack<>();
    Stack<Integer> tmp=new Stack<>();

    public void push(int node) {
        mystack.push(node);
        //【等于!】
        //["PSH2","PSH3","PSH6","PSH2","PSH4","PSH5","POP","POP","POP","MIN"] 
        if(tmp.isEmpty() || tmp.peek()>=node)
        {
            tmp.push(node);
        }
    }

    public void pop() {
        if(mystack.peek().equals(tmp.peek()))
        {
            tmp.pop();
        }
        mystack.pop();
    }

    public int top() {
        return mystack.peek();
    }

    public int min() {
        return tmp.peek();
    }
}

图片说明

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务