1. Title:

Implement a queue with two stacks. Implement appendTail and deleteHead to insert an integer at the end of the queue and delete an integer at the head of the queue. (If there are no elements in the queue, the deleteHead operation returns -1)

2. Ideas:
  • Stack is fifO, queue is fifO;
  • Two stacks, one for inserting and one for deleting elements;
  • The first in, first out (FIFO) rule applies to queues by manually drawing stack1 elements to Stack2 and then removing stack2 elements.

3. Code implementation:
var CQueue = class queue{
     constructor(){
         this.stack1 = [];
         this.stack2 = []
     }
     appendTail(value){
         this.stack1.push(value)
     }
     deleteHead(){
        if(this.stack2.length === 0){
            while(this.stack1.length >0){
                this.stack2.push(this.stack1.pop())
            }
        }
        if(this.stack2.length > 0){
            return this.stack2.pop()     
        }else{
            return -1
        }
     }
 }
Copy the code