【问题标题】:How to use a list as a stack in Scala如何在 Scala 中将列表用作堆栈
【发布时间】: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


【解决方案1】:

scala.List 是不可变集合,这意味着你不能像普通的mutable.Stack 那样推送或弹出。每次更改时都会创建新列表。

//it is immutable, then we need to use var instead of val
var stack = List.empty[Int]

//we can always assign fresh value to it. It is immutable... this is the only thing we can do here.
stack = List(1,2,3)

//peek() will look like this
def peek() = stack.head

//push(5) will assign new list that has prepended our value:
def push(x:Int) = stack = 5 :: stack

//pop() will be slightly complicated:
def pop() = {
  val popped = stack.head
  stack = stack.tail
  popped
}

PS:编写这样的对全局变量进行操作的函数可能不是一个好主意。这只是为了展示......在实际代码中,您将直接使用ListSeq Api。

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2019-03-09
    • 2010-09-18
    • 2016-10-15
    • 1970-01-01
    相关资源
    最近更新 更多