题解 | #【模板】栈#
【模板】栈
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()