设计一个有getMin的栈

【题目】

实现一个栈,在基本功能基础上,能返回栈中最小元素

【要求】

各方法操作的时间复杂度为O(1)
可以使用现成的栈结构

【例子】

public class demo {
    public static void main(String[] args) {
        Mystack ms=new Mystack();
        ms.push(3);
        ms.push(4);
        ms.push(5);
        ms.push(1);
        ms.push(2);

        System.out.println(ms.getMin());//1
        System.out.println(ms.pop());//2
        System.out.println(ms.pop());//1
        System.out.println(ms.pop());//5
        System.out.println(ms.pop());//4
        System.out.println(ms.pop());//3
        System.out.println(ms.pop());//Your stack is empty
    }

【代码】

import java.util.Stack;

public class Mystack {
       private Stack<Integer> stackData;//私有成员变量,用来保存当前栈中的元素,正常栈
       private Stack<Integer> stackMin;//用于保存每一步的最小值

       public Mystack(){//构造方法
           this.stackData=new Stack<Integer>();
           this.stackMin=new Stack<Integer>();
       }

       public void push(int newNum){//入栈方法
           if(this.stackMin.isEmpty()||newNum<this.getMin()){
               this.stackMin.push(newNum);
           }
           this.stackData.push(newNum);
       }

       public int pop(){//出栈方法
           if(this.stackData.isEmpty()){
               throw new RuntimeException("Your stack is empty");
           }
           int value=this.stackData.pop();
           if(value==this.getMin()){//若当前stackData弹出值是Min,则在stackMin栈中也弹出
               this.stackMin.pop();
           }
           return value;
       }

       public int getMin(){//获得最小值
           if(this.stackMin.isEmpty()){
               throw new RuntimeException("Your stack is empty");
           }
           return this.stackMin.peek();
       }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值