1、使用Stack 泛型指定数据类型Integer,让它只能存Integer 2、根据题目改造pop和top
注意题目的:
如果操作为push,则不输出任何东西。
如果为另外两种,若栈为空,则输出 "error“
否则按对应操作输出。
package com.newcoder.huawei;
import java.util.*;
public class AB1 {
private static Stack<Integer> stack = new Stack<>();
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());//获取总的操作次数
while (scan.hasNextLine()) {//获取每一次操作
String str = scan.nextLine();
String arr[] = str.split(" ");
if (arr[0].equals("push")) {
stack.push(Integer.parseInt(arr[1]));
} else if (arr[0].equals("pop")) {
pop();
} else {
top();
}
}
scan.close();
}
public static void pop() {
if (!stack.isEmpty()) {
System.out.println(stack.pop());
}else {
System.out.println("error");
}
}
public static void top() {
if (!stack.isEmpty()) {
System.out.println(stack.peek());
}else {
System.out.println("error");
}
}
}