剑指offer-包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。

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.empty())
            stack2.push(node);
        if(node<stack2.peek())
            stack2.push(node);
        
    }
    
    public void pop() {
        if(stack1.peek()==stack2.peek()){
            stack1.pop();
            stack2.pop();
        }
        else{
            stack1.pop();
        }
        
    }
    
    public int top() {
        return stack1.peek();
        
    }
    
    public int min() {
        return stack2.peek();
        
    }
}

 

posted @ 2020-02-21 21:04  清心lh  阅读(101)  评论(0编辑  收藏  举报