#K8551. Queue Implementation Using Two Stacks
Queue Implementation Using Two Stacks
Queue Implementation Using Two Stacks
You are required to implement a queue using two stacks. The queue should support the following operations:
- enqueue x: Insert the integer
x
at the end of the queue. - dequeue: Remove and return the element at the front of the queue. If the queue is empty, return
None
. - peek: Return the element at the front of the queue without removing it. If the queue is empty, return
None
. - is_empty: Return
True
if the queue is empty, otherwiseFalse
. - size: Return the number of elements in the queue.
Implementation Note: You must implement the queue using two stacks. That is, your queue should maintain two stacks internally to manage the enqueue and dequeue operations efficiently. If any formula is needed, use LaTeX format (for example, the size can be viewed as \(\text{size} = |\text{in_stack}|+|\text{out_stack}|\)).
The operations (except for enqueue
) produce an output. You must read input from stdin
and produce output to stdout
.
inputFormat
The input begins with an integer n
representing the number of operations. Each of the following n
lines contains a single command in one of the following formats:
enqueue x
wherex
is an integerdequeue
peek
is_empty
size
Note: The enqueue
command does not produce an output.
outputFormat
For each command that produces an output (dequeue
, peek
, is_empty
, and size
), print the result on a new line. For commands that return no value, nothing should be printed.
If an operation returns a null value (i.e. no element to dequeue or peek), output the string None
.
5
enqueue 1
enqueue 2
peek
dequeue
size
1
1
1
</p>