题解 | #【模板】栈#

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

import java.util.Scanner;
import java.util.ArrayList;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int a = Integer.valueOf(in.nextLine());
            Stack mySt = new Stack(a);
            for(int i = 0;i<a;i++){
                String str = in.nextLine();
                mySt.operate(str);
            }
        }
    }
}

class Stack {
    //private int size = 0;
    private int maxSize;
    private int[] data;
    private int topIndex = -1;

    public Stack(int maxSize) {
        this.maxSize = maxSize;
        this.data = new int[maxSize];
    }

    public void top() {
        if (this.topIndex == -1) {
            System.out.println("error");
        } else {
            System.out.println(data[topIndex]);
        }
    }

    public void push(int num) {
        if (this.topIndex == maxSize) {
            System.out.println("error");
        } else {
            this.topIndex++;
            this.data[topIndex] = num;
        }
    }

    public void pop() {
        if (this.topIndex == -1) {
            System.out.println("error");
        } else {
            System.out.println(this.data[topIndex]);
            this.topIndex--;
        }
    }

    public void operate(String opStr) {

        String[] strArr = opStr.split(" ");

        switch (strArr[0]) {
            case "push":
                this.push(Integer.valueOf(strArr[1]));
                break;
            case "pop":
                this.pop();
                break;
            case "top":
                this.top();
                break;
            default:
                break;
        }
    }

}

全部评论

相关推荐

但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
牛客92804383...:在他心里你已经是他的员工了
点赞 评论 收藏
分享
uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务