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

实现一个特殊的栈, 在实现栈的基本功能的基础上, 再实现返回栈中最小元素的操作。
【要求】
1. pop、push、getMin操作的时间复杂度都是O(1)。
2. 设计的栈类型可以使用现成的栈结构。

思路:同时维护两个栈结构,一个栈就是正常的栈,另一个栈放当前的最小值,和第一个栈同步操作。

package LinearStructure;

import java.util.Stack;

public class GetMinStack {

    Stack<Integer> stackData=new Stack<Integer>();
    Stack<Integer> stackMin=new Stack<Integer>();

    public void push(int obj){
        if(stackMin.isEmpty()){//如果当前最小值栈为空,则直接入栈
            stackMin.push(obj);
        }else if(obj>stackMin.peek()){//如果当前值大于当前最小值栈的栈顶元素,则再压入一个最小值栈栈顶元素
            stackMin.push(stackMin.peek());
        }else //当前值小于等于最小值栈栈顶元素,当前值入栈
            stackMin.push(obj);
        stackData.push(obj);
    }

    public int pop(){
        if(stackData.isEmpty()){
            throw new RuntimeException("stack is empty!");
        }
        stackMin.pop();
        return stackData.pop();
    }

    public int getMin(){
        if(stackData.isEmpty()){
            throw new RuntimeException("stack is empty!");
        }
        return stackMin.peek();
    }

    public static void main(String[] args) {
        GetMinStack s = new GetMinStack();
        s.push(6);
        s.push(5);
        s.push(2);

        int res = s.getMin();
        System.out.println(res);

        s.push(7);

        res =  s.getMin();
        System.out.println(res);

        s.pop();
        s.pop();

        res =  s.getMin();
        System.out.println(res);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值