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