题解 | #【模板】栈#

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf?tpId=308&tqId=2111163&ru=/exam/oj&qru=/ta/algorithm-start/question-ranking&sourceUrl=%2Fexam%2Foj

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < n; i++){
            String str = in.next();
            if(str.equals("push")){
                int num = in.nextInt();
                stack.push(num);
            }else if(str.equals("pop")){
                if(stack.size() > 0){
                     System.out.println(stack.pop()); //弹出栈顶元素
                }else{
                    System.out.println("error");
                }
            }else if(str.equals("top")){
                 if(stack.size() > 0){
                     System.out.println(stack.peek()); //查看栈顶元素,不弹出
                }else{
                    System.out.println("error");
                }
            }
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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