mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0232.用栈实现队列.md Scala版本
This commit is contained in:
@ -495,6 +495,45 @@ void myQueueFree(MyQueue* obj) {
|
|||||||
obj->stackOutTop = 0;
|
obj->stackOutTop = 0;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Scala:
|
||||||
|
```scala
|
||||||
|
class MyQueue() {
|
||||||
|
import scala.collection.mutable
|
||||||
|
val stackIn = mutable.Stack[Int]() // 负责出栈
|
||||||
|
val stackOut = mutable.Stack[Int]() // 负责入栈
|
||||||
|
|
||||||
|
// 添加元素
|
||||||
|
def push(x: Int) {
|
||||||
|
stackIn.push(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 复用代码,如果stackOut为空就把stackIn的所有元素都压入StackOut
|
||||||
|
def dumpStackIn(): Unit = {
|
||||||
|
if (!stackOut.isEmpty) return
|
||||||
|
while (!stackIn.isEmpty) {
|
||||||
|
stackOut.push(stackIn.pop())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 弹出元素
|
||||||
|
def pop(): Int = {
|
||||||
|
dumpStackIn()
|
||||||
|
stackOut.pop()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取队头
|
||||||
|
def peek(): Int = {
|
||||||
|
dumpStackIn()
|
||||||
|
val res: Int = stackOut.pop()
|
||||||
|
stackOut.push(res)
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
// 判断是否为空
|
||||||
|
def empty(): Boolean = {
|
||||||
|
stackIn.isEmpty && stackOut.isEmpty
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user