题解 | 【模板】栈

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf?tpId=308&tqId=2111163&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        in.nextLine();

        Stack stack = new Stack(x);
        
        for(int i = 0; i < x; i++){
            String s = in.nextLine();
            // 将字符串按字符串中的字符串划分成字符串数组
            String[] sArr = s.split(" ");
            String command = sArr[0];
            if(command.equals("push")){
                stack.push(Integer.parseInt(sArr[1]));
            }else if(command.equals("pop")){
                stack.pop();
            }else if(command.equals("top")){
                stack.top();
            }
        }
        in.close();
    }

}

class Stack{
    // 栈属性
    // 栈中数据
    int[] data;
    // 栈顶元素
    int top;
    // 当前栈长度
    int currentLen = 0;
    // 栈最大长度,用来初始化栈
    int maxSize;

    // 栈构造器
    public Stack (int maxSize){
        this.maxSize = maxSize;
        data = new int[maxSize];
    }

    // 栈方法
    // 压栈
    public void push(int pNum){
        if(this.currentLen == this.maxSize){
            return;
        }else{
            data[currentLen] = pNum;
            currentLen++;
        }
    }

    // 弹栈
    public void pop(){
        if(this.currentLen == 0){
            System.out.println("error");
        }else{
            currentLen--;
            System.out.println(data[currentLen]);
        }
    }

    // 查看栈顶元素
    public void top(){
        if(this.currentLen == 0){
            System.out.println("error");
        }else{
            System.out.println(data[currentLen - 1]);
        }
    }
}

全部评论

相关推荐

饼子吃到撑:据我了解奥,我身边的护士大部分都是找关系进的医院,还掏了不少米
点赞 评论 收藏
分享
09-19 12:15
门头沟学院 Java
猫头夜鹰:请问收到意向要点接受拒绝吗,还是开奖之后再接受拒绝
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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