题目描述
用两个栈实现队列,支持队列的基本操作。
输入描述:
第一行输入一个整数N,表示对队列进行的操作总数。 下面N行每行输入一个字符串S,表示操作的种类。 如果S为"add",则后面还有一个整数X表示向队列尾部加入整数X。 如果S为"poll",则表示弹出队列头部操作。 如果S为"peek",则表示询问当前队列中头部元素是多少。
输出描述:
对于每一个为"peek"的操作,输出一行表示当前队列中头部元素是多少。
示例1
输入
复制
6 add 1 add 2 add 3 peek poll peek
输出
复制
1 2
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(scanner.readLine());
TwoStacksQueue twoStacksQueue = new TwoStacksQueue();
while (count > 0) {
--count;
String[] inputs = scanner.readLine().split("\\s+");
if ("add".equals(inputs[0])) {
twoStacksQueue.add(Integer.parseInt(inputs[1]));
} else if ("peek".equals(inputs[0])) {
System.out.println(twoStacksQueue.peek());
} else {
twoStacksQueue.pop();
}
}
}
}
class TwoStacksQueue {
private Stack<Integer> stackPush = new Stack<>();
private Stack<Integer> stackPop = new Stack<>();
public void add(Integer item) {
while (!stackPop.isEmpty()) {
stackPush.add(stackPop.pop());
}
stackPush.add(item);
while (!stackPush.isEmpty()) stackPop.add(stackPush.pop());
}
public Integer peek() {
return stackPop.isEmpty() ? null : stackPop.peek();
}
public Integer pop() {
return stackPop.pop();
}
}