牛客网-剑指offer-20-包含min函数的栈

来源:互联网 发布:一年java专业技能描述 编辑:程序博客网 时间:2024/05/17 07:56
时间限制:1秒 空间限制:32768K 热度指数:97068
本题知识点: 栈
 算法知识视频讲解

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
用2个栈
import java.util.Stack;


public class Solution {


    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
        if(stack2.isEmpty()) {
            stack2.push(node);
        }else {
            stack2.push(Math.min(node, stack2.peek()));
        }
    }
    
    public void pop() {
        stack1.pop();
        stack2.pop();
    }
    
    public int top() {
        return stack1.peek();
    }
    
    public int min() {
        return stack2.peek();
    }
}