18、包含min函数的栈

版权声明:版权所有 https://blog.csdn.net/qq_42253147/article/details/86466949

题目

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

思路

  • 左神的基础班资料,栈、队列markdown文件中
  • 使用两个栈结构实现一个得到栈中元素最小值的问题

代码

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 =new Stack<>();
    
    public void push(int node) {
        stack1.push(node);
        
        if(stack2.isEmpty()){
            stack2.push(node);
        }else if(node<this.min()){
            stack2.push(node);
        }else{
            int minnum = this.min();
            stack2.push(minnum);
        }
    }
    
    public void pop() {
        if(stack1.isEmpty()){
            throw new RuntimeException("stack1已经空了");
        }
        stack2.pop();
        stack1.pop();
    }
    
    public int top() {
        if(stack2.isEmpty()){
            throw new RuntimeException("stack2已经空了");
        }
        return stack2.peek();
    }
    
    public int min() {
        if(stack2.isEmpty()){
            throw new RuntimeException("stack2已经空了");
        }
        return stack2.peek();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42253147/article/details/86466949