1. Title description ๐Ÿ’ฏ

  • Implementation of a queue by two stacks, supporting basic operations of queues (add,poll, PEEK)

2. Analysis of ideas ๐Ÿค”

1. When a stackPush is pushed into a stackPop, press all the stackPush into 2. When exiting the queue, if stackPop has elements, there is no need to press stackPop into them

Three, code implementation ๐ŸŒ‚

let stackPush = []
let stackPop = []
If the queue is full, an exception is thrown
function add(ele){
   stackPush.unshift(ele)
}
// poll: pops the first element from the queue or returns NULL if the queue is empty
function poll(){
   if(stackPop[0]) {return stackPop.shift()
   }else if(stackPush[0]) {for (let index = 0; stackPush.length>0; index++) {
           let  ele = stackPush.shift()
           stackPop.unshift(ele)   
       }
       return stackPop.shift()
   }else{
       return null}}// View the first element. The first element is not removed, but null is returned if the queue is empty
function peek(){
   if(stackPop[0]) {return stackPop[0]}else if(stackPush[0]) {for (let index = 0; stackPush.length>0; index++) {
           let  ele = stackPush.shift()
           stackPop.unshift(ele)   
       }
       return stackPop[0]}else{
       return null}}Copy the code

Four, simple test ๐Ÿงช

let arr1= [5.6.4.3.1]
for (let ind = 0; ind < arr1.length; ind++) {
    const ele = arr1[ind];
    add(ele)
}S
console.log(stackPush)
console.log(poll())
console.log(peek())
Copy the code

Code download address

Thank ๐Ÿ™‡

  • Speed up your front-end development ๐Ÿš€
  • โœ handwriting vue with several processes

Like and support ๐Ÿ‘

  • blog
  • Js knowledge collection
  • CSS knowledge collection
  • Vue knowledge collection
  • Collection of algorithm problems