-
Notifications
You must be signed in to change notification settings - Fork 183
/
Copy pathSolution.java
50 lines (41 loc) · 1.26 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
public class Solution {
public static class MyQueue<T> {
Stack<T> stackNewestOnTop = new Stack<>();
Stack<T> stackOldestOnTop = new Stack<>();
public void push(T value) {
stackNewestOnTop.push(value);
}
public void pop() {
prepareStackOldestOnTop();
stackOldestOnTop.pop();
}
public T peek() {
prepareStackOldestOnTop();
return stackOldestOnTop.peek();
}
private void prepareStackOldestOnTop() {
if (stackOldestOnTop.empty()) {
while (!stackNewestOnTop.empty()) {
stackOldestOnTop.push(stackNewestOnTop.pop());
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
MyQueue<Integer> queue = new MyQueue<Integer>();
for (int i = 0; i < n; i++) {
int op = in.nextInt();
if (op == 1) {
queue.push(in.nextInt());
} else if (op == 2) {
queue.pop();
} else if (op == 3) {
System.out.println(queue.peek());
}
}
in.close();
}
}