题解 | #CD6 由两个栈组成的队列#
由两个栈组成的队列
http://www.nowcoder.com/practice/6bc058b32ee54a5fa18c62f29bae9863
使用两个栈,一个栈保存输入数据,另一个栈倒序保存原输入栈的数据
- 运行时间:1412ms,超过82.04% 用Java提交的代码
- 占用内存:29272KB,超过90.63% 用Java提交的代码
import java.util.*;
import java.io.*;
public class Main {
Deque<Integer> input = new LinkedList<>();
Deque<Integer> reverse = new LinkedList<>();
public static void main(String[] args) throws IOException {
Main mn = new Main();
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
int row = Integer.parseInt(sc.readLine());
for(int i = 0; i < row; i++) {
String s = sc.readLine();
switch (s) {
case "peek":
mn.peek();
break;
case "poll":
mn.poll();
break;
default:
String[] ss = s.split(" ");
int n = Integer.valueOf(ss[1]);
mn.add(n);
break;
}
}
}
private void peek() {
if (reverse.isEmpty()) transfer();
System.out.println(reverse.peek());
}
private void poll() {
if (reverse.isEmpty()) transfer();
reverse.pop();
}
private void add(int n) {
input.push(n);
}
private void transfer() {
while(!input.isEmpty()) {
reverse.push(input.pop());
}
}
}