以下为ChatGPT自动生成的解答,正确与否请自行判断。 也许你也可以从大家的发帖中找到想要的答案!

BFE.devAI解答 - JavaScript 代码题
13. 利用栈(Stack)创建队列(Queue)

可以通过两个Stack来实现一个Queue,具体做法如下:

第一个Stack用于实现enqueue方法,每次调用enqueue时,将元素压入该Stack中。

第二个Stack用于实现dequeue和peek方法,每次调用这两个方法时,首先检查该Stack是否为空,如果为空,就将第一个Stack中的元素全部弹出并压入该Stack中,这样第二个Stack的栈顶元素就是第一个元素,可以相应地进行dequeue和peek操作。

代码实现如下:

class Stack {  constructor() {    this.items = []  }  push(element) {    this.items.push(element)  }  pop() {    return this.items.pop()  }  peek() {    return this.items[this.items.length - 1]  }  isEmpty() {    return this.items.length === 0  }  size() {    return this.items.length  }}class Queue {  constructor() {    this.stack1 = new Stack()    this.stack2 = new Stack()  }  enqueue(element) {    this.stack1.push(element)  }  dequeue() {    if (this.stack2.isEmpty()) {      while (!this.stack1.isEmpty()) {        this.stack2.push(this.stack1.pop())      }    }    return this.stack2.pop()  }  peek() {    if (this.stack2.isEmpty()) {      while (!this.stack1.isEmpty()) {        this.stack2.push(this.stack1.pop())      }    }    return this.stack2.peek()  }  size() {    return this.stack1.size() + this.stack2.size()  }}

测试代码如下:

const queue = new Queue()queue.enqueue(1)queue.enqueue(2)console.log(queue.peek()) // 1queue.enqueue(3)console.log(queue.dequeue()) // 1console.log(queue.dequeue()) // 2console.log(queue.peek()) // 3queue.enqueue(4)console.log(queue.size()) // 2console.log(queue.dequeue()) // 3console.log(queue.dequeue()) // 4console.log(queue.size()) // 0