题解 | #【模板】栈# 请你实现一个栈。

【模板】栈

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

import java.util.LinkedList;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Mystack<Integer> st = new Mystack<Integer>();
        int i = 1;
        String a = "";
        while (in.hasNextLine()) {
            //第一次输入的数代表操作数,不做处理
            if (i == 1) {
                in.nextLine();
                i++;
            } else {
                a = in.nextLine();
                String [] a1 = a.split(" "); //对输入字符串拆分成数组
//                  for(String t:a1) {
//                          System.out.println(t);
//                  }
                //数组长度等于1表示 为出栈或取栈顶无需传入result()第三个参数
                if (a1.length == 1) {
                    System.out.println(result(st, a1[0]));
                } else {
                    result(st, a1[0], a1[1]); //大于1为入栈,需传入result()第三个参数
                }
                i++;

            }
        }
    }
    //判断对栈进行什么操作并返回操作值
    public static Object result(Mystack<Integer> st, String s, String ...params) {
        switch (s) {
            case "push": {
                    st.push(Integer.parseInt(params[0]));
                    return "";
                }
            case "pop": {
                    return st.pop();
                }
            case "top": {
                    return st.top();
                }
            default:
                return "error";
        }
    }
}
//用linkedList模拟栈
class Mystack<T> {
    LinkedList<T> linkedlist = new LinkedList<T>();
    void push(T o) {
        linkedlist.addLast(o);
    }
    Object pop() {
        if (!linkedlist.isEmpty())
            return linkedlist.removeLast();
        else
            return "error";
    }
    Object top() {
        if (!linkedlist.isEmpty())
            return linkedlist.getLast();
        else
            return "error";
    }
}

#悬赏#
全部评论

相关推荐

点赞 评论 收藏
分享
05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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