Javascript solution


  • 0
    C
    var Queue = function() {
        this.inbox = [];
        this.outbox = [];
    };
    
    Queue.prototype.push = function(x) {
        this.inbox.push(x)
    };
    
    Queue.prototype.pop = function() {
        while (this.inbox.length) {
            this.outbox.push(this.inbox.pop());
        }
        var first = this.outbox.pop();
        while (this.outbox.length) {
            this.inbox.push(this.outbox.pop());
        }
        return first;
    };
    
    Queue.prototype.peek = function() {
        return this.inbox[0];
    };
    
    Queue.prototype.empty = function() {
        return this.inbox.length === 0;
    };
    

  • 0

    We can use shift / splice for pop method

    Queue.prototype.pop = function() {
        return this.inbox.splice(0, 1); or  return this.inbox.shift();
    };

Log in to reply
 

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