【发布时间】:2021-12-21 14:05:18
【问题描述】:
谁能给我解释一下如何在一个堆栈中实现多个队列
// implement stacks using plain arrays with push and pop functions
var Stack1 = [];
var Stack2 = [];
// implement enqueue method by using only stacks
// and the push and pop functions
function Enqueue(element) {
Stack1.push(element);
}
// implement dequeue method by pushing all elements
// from stack 1 into stack 2, which reverses the order
// and then popping from stack 2
function Dequeue() {
if (Stack2.length === 0) {
if (Stack1.length === 0) { return 'Cannot dequeue because queue is empty'; }
while (Stack1.length > 0) {
var p = Stack1.pop();
Stack2.push(p);
}
}
return Stack2.pop();
}
Enqueue('a');
Enqueue('b');
Enqueue('c');
Dequeue();
【问题讨论】:
-
问题被标记为
c++,但这似乎不正确,请添加正确的语言标签
标签: javascript data-structures queue stack