算法空间/Leetcode/两个栈实现队列:修订间差异
来自康健生活
创建页面,内容为“== 题目描述 == 用两个栈实现队列,完成队列的 push 和 pop 功能。” |
|||
| 第1行: | 第1行: | ||
== 题目描述 == | == 题目描述 == | ||
用两个栈实现队列,完成队列的 push 和 pop 功能。 | 用两个栈实现队列,完成队列的 push 和 pop 功能。 | ||
<syntaxhighlight lang="javascript"> | |||
const Queue = function () { | |||
this.inStack = []; | |||
this.outStack = []; | |||
} | |||
Queue.prototype.push = function (_v) { | |||
this.inStack.push(_v); | |||
} | |||
Queue.prototype.pop = function (_v) { | |||
const {inStack, outStack} = this; | |||
if (outStack.length) return outStack.pop(); | |||
else { | |||
while (inStack.length) { | |||
outStack.push(inStack.pop()); | |||
} | |||
return outStack.pop() || -1; | |||
} | |||
} | |||
// | |||
const foo = new Queue();</syntaxhighlight> | |||
2024年2月22日 (四) 13:20的版本
题目描述
用两个栈实现队列,完成队列的 push 和 pop 功能。
const Queue = function () {
this.inStack = [];
this.outStack = [];
}
Queue.prototype.push = function (_v) {
this.inStack.push(_v);
}
Queue.prototype.pop = function (_v) {
const {inStack, outStack} = this;
if (outStack.length) return outStack.pop();
else {
while (inStack.length) {
outStack.push(inStack.pop());
}
return outStack.pop() || -1;
}
}
//
const foo = new Queue();
No categories