采用自带的Stack库

【模板】栈

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

采用自带的Stack库 public class Main { private Stack stack = new Stack<>();

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int N = scan.nextInt();
    Main main = new Main();
    for (int i = 0; i < N + 1; i++) {
        main.checkCommand(scan.nextLine());
    }
    scan.close();
}

public void checkCommand(String s) {
    String[] command = s.split(" ");
    if (command[0].equals("push")) {
        push(Integer.parseInt(command[1]));
    }else if (command[0].equals("pop")) {
        pop();
    }else if (command[0].equals("top")) {
        top();
    }
}

public void push(int x) {
    stack.push(x);
}

public void pop() {
    if (!stack.isEmpty()) {
        System.out.println(stack.pop());
    }else {
        System.out.println("error");
    }
}

public void top() {
    if (!stack.isEmpty()) {
        System.out.println(stack.peek());
    }else {
        System.out.println("error");
    }
}

}

全部评论
用自带的stcak库真方便
1 回复 分享
发布于 2022-12-13 15:07 浙江

相关推荐

点赞 评论 收藏
分享
notbeentak...:就抓,嗯抓,开不开匿名都要抓,一点坏事不让说,就对公司顶礼膜拜佩服的五体投地就对了
点赞 评论 收藏
分享
评论
5
1
分享

创作者周榜

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