题解 | #包含min函数的栈 (额外用一个栈存储状态)#

包含min函数的栈

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

import java.util.*;
import java.util.Stack;

public class Solution {

    Stack<Integer> stack=new Stack<Integer>();
    Stack<Integer> minStack=new Stack<Integer>();
    public void push(int node) {
        stack.push(node);
        if (minStack.empty())
            minStack.push(node);
        else{
            int min = minStack.peek();
            if (min<=node){
                minStack.push(min);
            }
            else{
                minStack.push(node);
            }
        }
    }
    
    public void pop() {
        stack.pop();
        minStack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        return minStack.peek();
    }
}

全部评论

相关推荐

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