Merge pull request #1338 from wzqwtt/patch13

添加(0232.用栈实现队列、0225.用队列实现栈)Scala版本
This commit is contained in:
程序员Carl
2022-06-06 11:37:03 +08:00
committed by GitHub
2 changed files with 122 additions and 0 deletions

View File

@ -815,6 +815,89 @@ class MyStack {
}
}
```
Scala:
使用两个队列模拟栈:
```scala
import scala.collection.mutable
class MyStack() {
val queue1 = new mutable.Queue[Int]()
val queue2 = new mutable.Queue[Int]()
def push(x: Int) {
queue1.enqueue(x)
}
def pop(): Int = {
var size = queue1.size
// 将queue1中的每个元素都移动到queue2
for (i <- 0 until size - 1) {
queue2.enqueue(queue1.dequeue())
}
var res = queue1.dequeue()
// 再将queue2中的每个元素都移动到queue1
while (!queue2.isEmpty) {
queue1.enqueue(queue2.dequeue())
}
res
}
def top(): Int = {
var size = queue1.size
for (i <- 0 until size - 1) {
queue2.enqueue(queue1.dequeue())
}
var res = queue1.dequeue()
while (!queue2.isEmpty) {
queue1.enqueue(queue2.dequeue())
}
// 最终还需要把res送进queue1
queue1.enqueue(res)
res
}
def empty(): Boolean = {
queue1.isEmpty
}
}
```
使用一个队列模拟:
```scala
import scala.collection.mutable
class MyStack() {
val queue = new mutable.Queue[Int]()
def push(x: Int) {
queue.enqueue(x)
}
def pop(): Int = {
var size = queue.size
for (i <- 0 until size - 1) {
queue.enqueue(queue.head) // 把头添到队列最后
queue.dequeue() // 再出队
}
queue.dequeue()
}
def top(): Int = {
var size = queue.size
var res = 0
for (i <- 0 until size) {
queue.enqueue(queue.head) // 把头添到队列最后
res = queue.dequeue() // 再出队
}
res
}
def empty(): Boolean = {
queue.isEmpty
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -495,6 +495,45 @@ void myQueueFree(MyQueue* obj) {
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>