← 返回 oracle 的题目列表Implement a Queue Using Two Stacks
类型:online_judge
Question: Implement a Queue Using Two Stacks
Implement a first-in-first-out (FIFO) queue using only two stacks. Support these operations:
PUSH x: Enqueue integer x.
POP: Remove and print the front element. The queue is guaranteed to be non-empty.
PEEK: Print the front element without removing it. The queue is guaranteed to be non-empty.
EMPTY: Print true if the queue is empty; otherwise print false.
Each PUSH, POP, PEEK, and EMPTY operation must run in amortized O(1) time, with O(n) additional space.
Input Format
The first line contains an integer q, the number of operations.
Each of the next q lines contains one operation: PUSH x, POP, PEEK, or EMPTY.
Output Format
For every POP, PEEK, and EMPTY operation, print the corresponding result on its own line.
Constraints
1 <= q <= 2 * 10^5
-10^9 <= x <= 10^9
Every POP and PEEK operation is guaranteed to occur when the queue is non-empty.
Example
Input:
8
PUSH 1
PUSH 2
PEEK
POP
EMPTY
PUSH 3
POP
POP
Output:
1
1
false
2
3
Example
Input
8
PUSH 1
PUSH 2
PEEK
POP
EMPTY
PUSH 3
POP
POP
Output
1
1
false
2
3