code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

225 Implement Stack Using Queues

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

var MyStack = function() {
  this.queue = []
}

/**
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
  const l = this.queue.length
  this.queue.push(x)
  for (let i = 0; i < l; i++) {
    const element = this.queue.shift()
    this.queue.push(element)
  }
}

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
  return this.queue.shift()
}

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
  return this.queue[0]
}

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
  return this.queue.length == 0
}

var obj = new MyStack()
obj.push(3)
obj.push(4)
console.log(obj.queue)
var param_2 = obj.pop()
var param_3 = obj.top()
var param_4 = obj.empty()

Created 2022-03-21T11:01:56+00:00 · Edit