首页 > 解决方案 > 如何在 Scala 中将列表用作堆栈

问题描述

我正在尝试在 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

解决方案


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。


推荐阅读