6. Use two stacks to implement the queue

subject

Two stacks are used to implement a queue to complete Push and Pop operations of the queue. The elements in the queue are of type int.

Basic idea

Stack 1:

For in-queue storage

Stack 2:

When leaving the queue, the data of stack 1 are sequentially pushed out of the stack and merged into stack 2

The data at the bottom of stack 1 when stack 2 is pushed out is the data to be pushed out of the queue.

Note:

Stack 2 is empty to supplement the data of stack 1, otherwise the current order will be disturbed.

image

Code

const stack1 = [];
const stack2 = [];

function push(node)
{
stack1.push(node);
}
function pop()
{
if(stack2.length === 0){
while(stack1.length>0){
stack2.push(stack1.pop());
}
}
return stack2.pop() || null;
}