题目1512:用两个栈实现队列
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
public class S7 {
static Stack<Integer> s1 = new Stack<Integer>();
static Stack<Integer> s2 = new Stack<Integer>();
public static void main(String[] args) throws FileNotFoundException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("S7.in"));
System.setIn(in);
Scanner cin = new Scanner(System.in);
while (cin.hasNextLine()) {
int lines = Integer.parseInt(cin.nextLine());
for(int i=0; i<lines; i++){
String s = cin.nextLine();
process(s);
}
}
}
public static void process(String s){
if(s.startsWith("PUSH")){
String[] ss = s.split(" ");
int val = Integer.parseInt(ss[1]);
s1.push(val); // 直接压栈即可
}else if(s.startsWith("POP")){
if(s2.isEmpty()){ // 如果s2为空,则把s1里的元素全部压到栈2中
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
if(s2.isEmpty()){
System.out.println("-1");
}else{
System.out.println(s2.pop());
}
}
}
}
这样的提示,估计又是Java的原因吧。暂且不管了。