Home  >  Article  >  Web Front-end  >  Algorithm to implement queue using two stacks in js

Algorithm to implement queue using two stacks in js

不言
不言Original
2018-07-21 10:59:511758browse

This article shares with you the algorithm of using two stacks to implement queues in js. The content is very good. Friends in need can refer to it. I hope it can help everyone.

Problem Description

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

Analysis

Two stacks implement queues, that is, one in and one out, and the question does not mention the length limit of the two stacks, then for the two stacks s1 Regarding s2, there are two points to note: When

  • s1.push, if s2 is not empty and s1 is empty, in order to ensure the correct order, All elements of s2 are returned to s1, and then when s1.push

  • s2.pop, if s2 is empty and s1 is not empty, in order to ensure the correct order, the elements of s1 will be Put all the elements into s2, and then s2.pop

Code implementation

var s1 = [], s2 = [];
function transferStack(a, b) {
    while(a.length !== 0){
        b.push(a.pop());
    }
}
function push(val) {
    if(s1.length === 0 && s2.length !== 0){
        transferStack(s2, s1);
    }

    s1.push(val);
}

function pop(){
    if(s1.length !== 0 && s2.length === 0){
        transferStack(s1, s2);
    }

    return s2.pop();
}

Related recommendations:

How to use the $() function in jQuery

The above is the detailed content of Algorithm to implement queue using two stacks in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn