设计一个有getMin功能的栈,包含Sanner函数的写法

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

  这道题本身很简单,比较复杂的地方是,在牛客网上利用scanner函数输入数据的时候,有很多的坑。题目本身倒是真没花费我多少时间。希望我的这份代码能帮到你。如果你有更好的方法,还请不吝赐教。

代码如下:

import java.util.Scanner;
import java.util.Stack;

public class Main {
    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;

    public Main() {
        this.stackData = new Stack<Integer>();
        this.stackMin = new Stack<Integer>();
    }

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

    public int pop() {
        if (this.stackData.isEmpty()) {
            throw new RuntimeException("Your stack is Empty");
        }
        int value = this.stackData.pop();
        if (value == this.getMin()) {
            this.stackMin.pop();
        }
        return value;
    }

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

    public static void main(String[] args) {
        Main main = new Main();
        Scanner sc = new Scanner(System.in);

        int epoch = sc.nextInt();
        
		// 这句非常重要,跳到第二行
        sc.nextLine();

        for (int i = 0; i < epoch; i++) {
            String methods = sc.nextLine();
            String[] method = methods.split(" ");
            if (method[0].equals("push")) {
                int num = Integer.parseInt(method[1]);
                main.push(num);
            }
            if (method[0].equals("pop")) {
                main.pop();
            }
            if (method[0].equals("getMin")) {
                System.out.println(main.getMin());
            }
        }
    }
}

参考文章:Java中Scanner的用法:单行/多行输入

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值