JavaScript solutions beats 92.50% of submissions


  • 0
    S

    Performance Screenshot: http://lnk.ghiassy.com/1Qniylj

    var Queue = function(data) {
      if (data == undefined) {
        this.data = [];
      } else if (data instanceof Queue) {
        this.data = data.data;
      } else if (Array.isArray(data)) {
        this.data = data;
      } else {
        this.data = [data];
      }
    };
    
    Queue.prototype.push = function(value) {
      this.data = [value].concat(this.data); // put the value at the beginning of the array
    };
    
    Queue.prototype.peek = function() {
      return this.data[this.data.length-1];
    };
    
    Queue.prototype.pop = function() {
      return this.data.pop();
    };
    
    Queue.prototype.size = function() {
      return this.data.length;
    };
    
    Queue.prototype.isEmpty = function() {
      return this.data.length === 0;
    };
    
    
    /**
     * @constructor
     */
    var Stack = function(data) {
      if (data == undefined) {
        this.data = new Queue();
      } else {
        this.data = new Queue(data);
      }
    };
    
    /**
     * @param {number} x
     * @returns {void}
     */
    
    Stack.prototype.push = function(x) {
      if (x == undefined) {
        return;
      }
    
      var tmp = new Queue(x);
      while (this.data.size() > 0) {
        tmp.push(this.data.pop());
      }
      this.data = new Queue(tmp);
    };
    
    /**
     * @returns {void}
     */
    Stack.prototype.pop = function() {
      return this.data.pop();
    };
    
    /**
     * @returns {number}
     */
    Stack.prototype.top = function() {
      return this.data.peek();
    };
    
    /**
     * @returns {boolean}
     */
    Stack.prototype.empty = function() {
      return this.data.isEmpty();
    };

Log in to reply
 

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