Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 08147d1

Browse files
committed
添加 0232.用栈实现队列.md Scala版本
1 parent 98458cd commit 08147d1

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

‎problems/0232.用栈实现队列.md‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,45 @@ void myQueueFree(MyQueue* obj) {
495495
obj->stackOutTop = 0;
496496
}
497497
```
498-
498+
Scala:
499+
```scala
500+
class MyQueue() {
501+
import scala.collection.mutable
502+
val stackIn = mutable.Stack[Int]() // 负责出栈
503+
val stackOut = mutable.Stack[Int]() // 负责入栈
504+
505+
// 添加元素
506+
def push(x: Int) {
507+
stackIn.push(x)
508+
}
509+
510+
// 复用代码,如果stackOut为空就把stackIn的所有元素都压入StackOut
511+
def dumpStackIn(): Unit = {
512+
if (!stackOut.isEmpty) return
513+
while (!stackIn.isEmpty) {
514+
stackOut.push(stackIn.pop())
515+
}
516+
}
517+
518+
// 弹出元素
519+
def pop(): Int = {
520+
dumpStackIn()
521+
stackOut.pop()
522+
}
523+
524+
// 获取队头
525+
def peek(): Int = {
526+
dumpStackIn()
527+
val res: Int = stackOut.pop()
528+
stackOut.push(res)
529+
res
530+
}
531+
532+
// 判断是否为空
533+
def empty(): Boolean = {
534+
stackIn.isEmpty && stackOut.isEmpty
535+
}
536+
}
537+
```
499538
-----------------------
500539
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /