剑指offer--包含min函数的栈

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

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

import java.util.Stack;

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

猜你喜欢

转载自blog.csdn.net/TK_lTlei/article/details/84781387