题解 | #【模板】栈# 请你实现一个栈。
【模板】栈
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"; } }#悬赏#