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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

/**
 * 栈是Vector的一个子类,实现了一个标准的先进后出的
 * 案例操作实例:
 * 实现一个栈,实现栈的基本功能上,再实现返回栈中最小值的元素的操作
 */
public class TestStack {
    public static void main(String[] args) throws IOException {
        MyStack myStack = new MyStack();
        BufferedReader scanner= new BufferedReader(new InputStreamReader(System.in));
        int N=Integer.parseInt(scanner.readLine());
        for(int i=0;i<N;i++){
            String []inputData=scanner.readLine().split(" ");
            if(inputData[0].equals("push")){
                myStack.push(Integer.parseInt(inputData[1]));
            }
            if(inputData[0].equals("pop")){
                myStack.pop();
            }
            if(inputData[0].equals("getMin")){
                myStack.getMin();
            }
        }
        scanner.close();
    }
}

class MyStack {
    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;

    public MyStack() {
        this.stackData = stackData;
        this.stackMin = stackMin;
    }

    public void push(int newNum) {
        if (this.stackMin.isEmpty()) {
            this.stackMin.push(newNum);
        } else if (newNum <= this.getMin()) {
            this.stackMin.push(newNum);
        }
        this.stackData.push(newNum);
    }

    public int pop() {
        if(this.stackData.isEmpty()){
            throw new RuntimeException("你的栈为空");
        }
        int value=this.stackData.pop();
        if(value==this.getMin()){
            this.stackData.pop();
        }
        return value;
    }

    public int getMin() {
        if (this.stackMin.isEmpty()) {
            throw new RuntimeException("你的栈为空");
        }
        return this.stackMin.peek();//返回的是栈顶的元素
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值