Share my Javascript solution with only one queue


  • 1
    W

    I only use one queue, this is enough. when element is remove, you can push them in queue in the sometime. code like this:

    var Stack = function() {
        this.queue = [];
    };
    
    Stack.prototype.push = function(x) {
        this.queue.push(x);
    };
    
    Stack.prototype.pop = function() {
        for (var i = 1, len = this.queue.length; i < len; i += 1) {
            this.queue.push(this.queue.shift());
        }
        this.queue.shift();
    };
    
    Stack.prototype.top = function() {
        for (var i = 1, len = this.queue.length; i < len; i += 1) {
            this.queue.push(this.queue.shift());
        }
        var ele = this.queue.shift();
        this.queue.push(ele);
    
        return ele;
    };
    
    Stack.prototype.empty = function() {
        return this.queue.length === 0 ? true : false;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.