牛客网:AB1 【模板】栈

这篇博客展示了如何使用Java实现一个简单的栈数据结构,包括入栈、出栈和查看栈顶元素的操作。示例代码中定义了一个`MyStack`类,并提供了相应的方法来执行这些操作。此外,还包含了一个`strTransForInt`辅助方法用于将字符串转换为整数。

栈的数据结构就是先进后出,先了解一下他的数据结构。


import java.util.Scanner;

/**
 * @author xienl
 * @description 栈
 * @date 2022/5/16
 */

public class Main {
    public static void main(String[] args) {
        final String push = "push", pop = "pop", top = "top";
        Scanner scanner = new Scanner(System.in);
        // 输入次数
        int num = scanner.nextInt();
        MyStack myStack = new MyStack(num);
        scanner.nextLine(); // 这个是个scanner的大坑,如果按了会车一定要加

        for (int i = 0; i < num; i++){
            String next = scanner.nextLine();
            String[] split = next.split("\\s+");
            if (split == null || split[0].isEmpty()){
                return;
            }

            String str = split[0];
            if (push.equals(str)){
                if (split[1] == null || strTransForInt(split[1]) == -1){
                    return;
                }
                myStack.push(strTransForInt(split[1]));
            } else if (pop.equals(str)){
                myStack.pop();
            } else if (top.equals(str)){
                myStack.top();
            } else {
                return;
            }
        }

    }

    /**
     * 字符串转整数
     * @return
     */
    static int strTransForInt(String str){
        int i = -1;
        try {
            i = Integer.parseInt(str);
        }finally {
            return i;
        }
    }

}

// 栈类
class MyStack{

    private int size ; // 栈的大小
    private int index = -1; // 下标位
    private int[] arr; // 栈初始化,因为使用的是数组

    /**
     * @date 2022/5/16
     * @param
     */
    public MyStack(){};

    public MyStack(int size){
        this.size = size;
        arr = new int[size];
    };

    /**
     * 判断栈是否是空的
     * @return
     */
    public boolean isEmpty(){
        return index == -1;
    }

    /**
     * 入栈操作
     * @param value
     */
    public void push(int value){
        arr[++index] = value;
    }

    /**
     * 出栈操作
     * @return
     */
    public void pop(){
        if (isEmpty()){
            System.out.println("error");
            return;
        }
        System.out.println(arr[index--]);
    }

    /**
     * 查看栈顶是多少
     * @return
     */
    public void top(){
        if (isEmpty()){
            System.out.println("error");
            return;
        }
        System.out.println(arr[index]);
    }



}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值