我正在学习算法和数据结构。如何在JavaScript中使用队列?
我知道你可以像这样做。
var stack = [];
stack.push(2); // stack is now [2]
stack.push(5); // stack is now [2, 5]
var i = stack.pop(); // stack is now [2]
alert(i); // displays 5
var queue = [];
queue.push(2); // queue is now [2]
queue.push(5); // queue is now [2, 5]
var i = queue.shift(); // queue is now [5]
alert(i); // displays 2
但是使用 shift() 方法会移动所有元素,因此时间复杂度为 O(N),而不是 Java 中的 Dequeue 时间复杂度为 O(1)。
为什么 JavaScript 原生没有队列的概念,就像 Stack(array) 一样?
我只是很好奇,请给我指点迷津。
(我自己问了这个问题,但是找不到一个合理的原因,为什么 ES8 或 ES9 不会内置具有 Dequeue O(1) 和 enqueue O(1) 的队列,而无需自己实现)
PS:对于这个愚蠢的问题,我感到抱歉,但这一直在困扰着我!
.shift()
以避免重建整个数组? - nnnnnn