加州提子面包

JavaScript算法试题系列-06

题目要求:

1
2
3
4
5
6
7
// 栈与队列使用两个栈实现入队与出队var inputStack = []; // First stack
var outputStack = []; // Second stack
// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
return stackInput.push(item);
}

解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
function dequeue(stackInput, stackOutput) {
// Reverse the stack such that the first element of the output stack is the
// last element of the input stack. After that, pop the top of the output to
// get the first element that was ever pushed into the input stack
if (stackOutput.length <= 0) {
while(stackInput.length > 0) {
var elementToOutput = stackInput.pop();
stackOutput.push(elementToOutput);
}
}
return stackOutput.pop();
}
------ 本文结束 ------