Skip to content

Commit f4d98a7

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

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

problems/0225.用队列实现栈.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -815,6 +815,89 @@ class MyStack {
815815
}
816816
}
817817
```
818+
Scala:
818819

820+
使用两个队列模拟栈:
821+
```scala
822+
import scala.collection.mutable
823+
824+
class MyStack() {
825+
826+
val queue1 = new mutable.Queue[Int]()
827+
val queue2 = new mutable.Queue[Int]()
828+
829+
def push(x: Int) {
830+
queue1.enqueue(x)
831+
}
832+
833+
def pop(): Int = {
834+
var size = queue1.size
835+
// 将queue1中的每个元素都移动到queue2
836+
for (i <- 0 until size - 1) {
837+
queue2.enqueue(queue1.dequeue())
838+
}
839+
var res = queue1.dequeue()
840+
// 再将queue2中的每个元素都移动到queue1
841+
while (!queue2.isEmpty) {
842+
queue1.enqueue(queue2.dequeue())
843+
}
844+
res
845+
}
846+
847+
def top(): Int = {
848+
var size = queue1.size
849+
for (i <- 0 until size - 1) {
850+
queue2.enqueue(queue1.dequeue())
851+
}
852+
var res = queue1.dequeue()
853+
while (!queue2.isEmpty) {
854+
queue1.enqueue(queue2.dequeue())
855+
}
856+
// 最终还需要把res送进queue1
857+
queue1.enqueue(res)
858+
res
859+
}
860+
861+
def empty(): Boolean = {
862+
queue1.isEmpty
863+
}
864+
}
865+
```
866+
使用一个队列模拟:
867+
```scala
868+
import scala.collection.mutable
869+
870+
class MyStack() {
871+
872+
val queue = new mutable.Queue[Int]()
873+
874+
def push(x: Int) {
875+
queue.enqueue(x)
876+
}
877+
878+
def pop(): Int = {
879+
var size = queue.size
880+
for (i <- 0 until size - 1) {
881+
queue.enqueue(queue.head) // 把头添到队列最后
882+
queue.dequeue() // 再出队
883+
}
884+
queue.dequeue()
885+
}
886+
887+
def top(): Int = {
888+
var size = queue.size
889+
var res = 0
890+
for (i <- 0 until size) {
891+
queue.enqueue(queue.head) // 把头添到队列最后
892+
res = queue.dequeue() // 再出队
893+
}
894+
res
895+
}
896+
897+
def empty(): Boolean = {
898+
queue.isEmpty
899+
}
900+
}
901+
```
819902
-----------------------
820903
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)