采用自带的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 浙江

相关推荐

努力跨行专业的老菜鸡:cxmt给开了31k但是华子开了24k,这两个价格让我纠结要不要毁约cxmt去华为
点赞 评论 收藏
分享
评论
5
1
分享

创作者周榜

更多
牛客网
牛客企业服务