13. 利用栈(Stack)创建队列(Queue)
分享给更多人
中等难度 -通过 / -执行
在JavaScript中,我们可以用Array来充作Stack或者Queue.
const arr = [1, 2, 3, 4]
arr.push(5) // 变为 [1, 2, 3, 4, 5]
arr.pop() // 5, 数组变为 [1, 2, 3, 4]
上述是Stack的用法,以下则是Queue
const arr = [1, 2, 3, 4]
arr.push(5) // [1, 2, 3, 4, 5]
arr.shift() // 1, 现在数组是 [2, 3, 4, 5]
假设你有Stack,包含如下的方法
class Stack {
push(element) { /* 添加元素到stack */ }
peek() { /* 获取top 元素 */ }
pop() { /* 弹出top 元素 */}
size() { /* 获取元素数量 */}
}
你能否通过只使用Stack实现一个包含如下方法的Queue?
class Queue {
enqueue(element) { /* 添加元素到Queue,类似于Array.prototype.push */ }
peek() { /* 获取头元素*/ }
dequeue() { /* 弹出头元素,类似于Array.prototype.pop */ }
size() { /* 获取元素数量 */ }
}
注意
请只使用Stack,不要使用Array。