第一个题解
由两个栈组成的队列
http://www.nowcoder.com/questionTerminal/6bc058b32ee54a5fa18c62f29bae9863
import java.util.*;
public class Main{
static Stack<Integer> stack1 = new Stack<Integer>();
static Stack<Integer> stack2 = new Stack<Integer>();
public static void add(int a){
stack1.push(a);
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
}
public static int poll(){
if(stack2.isEmpty() && !stack1.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()) throw new RuntimeException("队列空");
return stack2.pop();
}
public static int peek(){
if(stack2.isEmpty() && !stack1.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()) throw new RuntimeException("队列空");
return stack2.peek();
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = Integer.valueOf(scan.nextLine());
for(;n>0;n--){
String str = scan.nextLine();
String[] splits = str.split(" ");
if("add".equals(splits[0])){
add(Integer.parseInt(splits[1]));
}else if("peek".equals(splits[0])){
System.out.println(peek());
}else{
poll();
}
}
}
}
查看24道真题和解析