Javascript 两层队列

Javascript 两层队列,javascript,data-structures,stack,queue,Javascript,Data Structures,Stack,Queue,我实现了一个具有两个堆栈的队列,如下所示: class QueueTwoStacks { constructor() { this.stack1 = [] this.stack2 = [] } enqueue(item) { this.stack1.push(item) const lastItem = this.stack1.pop() this.stack2.push(lastItem) const lastItem2 = this

我实现了一个具有两个堆栈的队列,如下所示:

class QueueTwoStacks {
  constructor() {
    this.stack1 = []
    this.stack2 = []
  }
  enqueue(item) {
    this.stack1.push(item)
    const lastItem = this.stack1.pop()
    this.stack2.push(lastItem)
    const lastItem2 = this.stack2.pop()
    this.stack1.push(lastItem2)
  }

  dequeue() {
    if(this.stack1.length === 0) throw Error
    return this.stack1.shift();
  }
}
我下面的课程给出了一个答案:

class QueueTwoStacks {
  constructor() {
    this.inStack = [];
    this.outStack = [];
  }

  enqueue(item) {
    this.inStack.push(item);
  }

  dequeue() {
    if (this.outStack.length === 0) {

      // Move items from inStack to outStack, reversing order
      while (this.inStack.length > 0) {
        const newestInStackItem = this.inStack.pop();
        this.outStack.push(newestInStackItem);
      }

      // If outStack is still empty, raise an error
      if (this.outStack.length === 0) {
        throw new Error("Can't dequeue from empty queue!");
      }
    }
    return this.outStack.pop();
  }
}

一个比另一个好吗?如果是,为什么?我觉得我的解决方案更好,因为你不必循环,但也许你不应该在排队方法中做所有的操作?

问题是你的实现每次都有O(n)个时间复杂性,因为你在调用
shift
。另一方面,
pop
是一个O(1)操作。有关更多详细信息,请查看

请注意,在您的实现中,您几乎可以完全摆脱
stack2
,并且它仍然可以工作(当然,具有与O(n)
dequeue
相同的缺点):

然而,第二个实现只是偶尔将元素移动到
扩展
(即仅当其为空时)并使用
pop
进行其
出列
操作。因此,虽然最坏的情况仍然是O(n),但在平均情况下,此实现中的出列应该是O(1),这比O(n)要好得多,特别是如果要多次调用它

class QueueTwoStacks {
  constructor() {
    this.stack1 = []
    // this.stack2 = []
  }
  enqueue(item) {
    this.stack1.push(item)
    // const lastItem = this.stack1.pop()
    // this.stack2.push(lastItem)
    // const lastItem2 = this.stack2.pop()
    // this.stack1.push(lastItem2)
  }

  dequeue() {
    if(this.stack1.length === 0) throw Error
    return this.stack1.shift();
  }
}