01面试-在栈的基本功能上还能返回栈中最小元素的操作

题目

实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。

要求

  1. pop、push、getMin操作的时间复杂度都是O(1)。

具体实现

//java实现
import java.util.*;
public class java_01{
    private Stack<Integer> stackData;//存放入栈的数据
    private Stack<Integer> stackMin;//存放栈中的最小值

    public java_01() {
        // 为栈分配空间
        this.stackData=new Stack<Integer>();
        this.stackMin=new Stack<Integer>();
    }
    // 每次都保证stackData栈中最小数在stackMin的栈顶
    public void push(int newNum) {
        if(this.stackMin.isEmpty()){
            this.stackMin.push(newNum);
        }else if(newNum <= this.getMin()){
            this.stackMin.push(newNum);
        }
        // 正常入栈stackData
        this.stackData.push(newNum);
    }
    // 出栈
    public int pop() {
        if(this.stackData.isEmpty() || this.stackMin.isEmpty()){
            throw new RuntimeException("Your stack is empty.");
        }
        int value=this.stackData.pop();
        //如果stackData栈中的值像外出栈的是stackData栈中的最小值
        // 那么就要更新stackMin栈中的值,使栈顶的数始终是stackData中的最小值
        if(value == this.getMin()){
            this.stackMin.pop();
        }
        return value;
    }
    //获取stackMin栈顶元素
    public int getMin(){
        if(this.stackMin.isEmpty()){
            throw new RuntimeException("Your stack is empty.");
        }
        return this.stackMin.peek();
    }

    public static void main(String[] args) {
        java_01 stack=new java_01();
        stack.push(3);
        stack.push(2);
        stack.push(1);
        stack.push(3);
        System.out.println("此时栈中最小值为:"+stack.getMin());
        stack.pop();
        stack.pop();
        stack.pop();
        System.out.println("此时栈中最小值为:"+stack.getMin());
    }
}

执行结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈行恩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值