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

包含min函数的栈

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

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

public class Solution {
    private Stack<Integer> stack = new Stack<>();

    public void push(int node) {
        stack.push(node);
    }

    public void pop() {
        stack.pop();
    }

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

    public int min() {
        Stack<Integer> tmp = new Stack<>();
        Integer pop = null;
        while(!stack.isEmpty()) {
            Integer cu = stack.pop();
            if(pop == null) {
                pop = cu;
            }
            if(pop > cu) {
                pop = cu;
            }
            tmp.push(cu);
        }
        while(!tmp.isEmpty()) {
            stack.push(tmp.pop());
        }
        return pop;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务