ES6 solution


  • 0
    Y
    class Stack {
      constructor() {
        this._q1 = []
        this._q2 = []
      }
    
      push(element) {
        const {_q1, _q2} = this
        const pushQ = _q2.length ? _q2 : _q1
        pushQ.push(element)
      }
    
      pop() {
        const {_q1, _q2} = this
        const [fromQ, toQ] = _q1.length ? [_q1, _q2] : [_q2, _q1]
        while (fromQ.length > 1) {
          toQ.push(fromQ.shift())
        }
        return fromQ.shift()
      }
    
      top() {
        const {_q1, _q2} = this
        return _q1.length ? _q1[_q1.length - 1] : _q2[_q2.length - 1]
      }
    
      empty() {
        const {_q1, _q2} = this
        return _q1.length === 0 && _q2.length === 0
      }
    }
    

Log in to reply
 

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