重拾算法之剑指Offier——包含min函数的栈

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Code_KK/article/details/55888527

题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

import java.util.Stack;

public class Solution {

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


    public void push(int node) {

        if (stack2.empty()){
            stack2.push(node);
        }else {
            int top1 = stack1.peek();
            if (top1 >= node){
                stack2.push(node);
            }else {
                stack2.push(top1);
            }
        }
        stack1.push(node);
    }

    public void pop() {
        stack2.pop();
        stack1.pop();

    }

    public int top() {
        return stack1.peek();

    }

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

猜你喜欢

转载自blog.csdn.net/Code_KK/article/details/55888527
今日推荐