Two stacks for queue title description
Implement a queue with two stacks to complete the push and pop operations of the queue. The elements in the queue are of type int.
Implementation code
functionStack () {varitems=[]; This. push=function(item) {Items.push (item); } This. pop=function(){ returnItems.pop (); } This. isempty=function(){ returnItems.length==0; }}varstack1=NewStack ();varStack2=NewStack ();functionPush (node) {Stack1.push (node);}functionpop () {//if both are empty, throw an error if(Stack1.isempty () &&Stack2.isempty ()) { Throw NewError ("Queue is empty"); } //if the stack 2 is empty, then stack 1 all the elements out of stacks, one at a time stack 2 if(Stack2.isempty ()) { while(!Stack1.isempty ()) {Stack2.push (Stack1.pop ())}} //if stack 2 is not empty, directly out of the stack returnStack2.pop ();}Ideas
Queue: The elements into the stack 1;
Outbound: Determine whether the stack 2 is empty, if it is empty, then all elements of the stack 1 POPs, and push into the stack 2, stack 2 out of the stack, if not empty, stack 2 directly out of the stack.
Related knowledge
Stack, aka stacks, is a linear table in which operations are limited. The limitation is that only one end of the table is allowed to insert and delete operations. This end is called the top of the stack, and the opposite end is called the bottom of the stack. Inserting a new element into a stack, also known as a stack, a stack, or a stack, is to put a new element on top of the stack, making it a new stack top element, deleting an element from a stack, or making a stack or fallback, by removing the top element of the stack and making its adjacent elements a new stack top element.
A queue is a special linear table, except that it allows for deletion only at the front end of the table (front), and in the back end (rear) of the table. The end of the insert operation is called the tail of the queue, and the end of the delete operation is called the team header.
-javascript (5) using two stacks to implement a queue