【发布时间】:2021-05-20 12:58:49
【问题描述】:
我正在尝试在 Scala 中使用 Stack,我已经在 Class 中完成了 Stack val s = Stack [Int] 并且效果很好,但我被要求使用一个作为 Stack 工作的 List ,如何制作?
import scala.collection.mutable.Stack
object string_Search
{
def main(args:Array[String])
{
trait push extends Stack {
def push(i:Int) {
s.push(i)
println(s)
}
}
trait pop extends Stack {
def pop() {
s.pop()
println(s)
}
}
trait view1 extends Stack {
def view() {
println(s)
}
}
class Stack {
protected val s = List[Int]()
}
val b = new Stack with push with pop with view1
println("Filling the Stack")
b.push(15)
b.push(20)
b.push(25)
b.push(30)
println("\nDeleting from the Stack")
b.pop()
b.pop()
b.pop()
println("\nOutput")
b.view()
}
}
【问题讨论】:
-
Scala 中的
List是一个堆栈。 -
如何从列表中添加(推送)和删除(弹出)?
-
push=prepend-peak=head-pop=head+tail -
PS:您的示例代码很奇怪。不知道为什么你的 API 过于复杂。需要时使用具有单一方法的接口(特征),但对于如此简单的 API,它相当过度设计。
标签: scala