算法空间/Leetcode/两个栈实现队列:修订间差异
来自康健生活
创建页面,内容为“== 题目描述 == 用两个栈实现队列,完成队列的 push 和 pop 功能。” |
小 Kangkk移动页面算法空间/两个栈实现队列至算法空间/Leetcode/两个栈实现队列,不留重定向 |
||
| (未显示同一用户的1个中间版本) | |||
| 第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> | |||