题解 | #【模板】栈#

【模板】栈

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

import java.util.Scanner;
import java.util.Stack;
public class Main{
    public static void main(String[] args){
        int line;
        Stack stack = new Stack<Integer>();
        Scanner sc = new Scanner(System.in);
        line = sc.nextInt();
        String text;
        String[] Arr;
        int i=0;
        for(i=0;i<line;i++){
            text = sc.nextLine();
            if(text.equals("")){
                i--;
                continue;
            }
            String sub = text.substring(0,3);
            if(sub.equals("pop")){
                if(stack.isEmpty())
                    System.out.println("error");
                else
                    System.out.println(stack.pop());
            }else if(sub.equals("top")){
                if(stack.isEmpty())
                    System.out.println("error");
                else
                    System.out.println(stack.peek());
            }else if(sub.equals("pus")){
                stack.push(text.substring(5));
            }
        }
    }
}

需要注意的是:
1.要考虑输入为空字符串的情况,即判断是否为""," "表示内容为空格的字符串 2.Stack中方法peek(),push(),pop(),empty()

全部评论

相关推荐

昨天 11:43
门头沟学院 C++
寄寄寄寄寄寄寄寄
投递腾讯等公司10个岗位
点赞 评论 收藏
分享
09-12 18:28
门头沟学院 Java
网友描述的太精准了👍
迷茫的大四🐶:不管活脏还是累,钱到位就行,钱到位啥都不用抱怨
投递字节跳动等公司10个岗位
点赞 评论 收藏
分享
08-29 16:36
门头沟学院 Java
野猪不是猪🐗:不如这样查看图片
点赞 评论 收藏
分享
点赞 评论 收藏
分享
09-12 12:09
郑州大学 Java
有啥题目啊?
投递小红书等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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