1.使用隊列
隊列是一種那個先進先出的隊列。
1)創建一個隊列。
scala> import scala.collection.mutable.Queue import scala.collection.mutable.Queue scala> var fruits = Queue[String]() fruits: scala.collection.mutable.Queue[String] = Queue() scala> fruits += "apple" res66: scala.collection.mutable.Queue[String] = Queue(apple) scala> fruits += ("orange","banana") res67: scala.collection.mutable.Queue[String] = Queue(apple, orange, banana) scala> fruits ++= List("cherry","cocount") res68: scala.collection.mutable.Queue[String] = Queue(apple, orange, banana, cherry, cocount) scala> fruits.enqueue("pine") scala> fruits res70: scala.collection.mutable.Queue[String] = Queue(apple, orange, banana, cherry, cocount, pine)
2)dequeue每次從隊列頭部刪除一個元素。
scala> val next = fruits.dequeue next: String = apple scala> fruits res72: scala.collection.mutable.Queue[String] = Queue(orange, banana, cherry, cocount, pine)
3)dequeueFirst和dequeueAll方法可以從隊列中刪除多個元素。
scala> var fruits = Queue[String]() fruits: scala.collection.mutable.Queue[String] = Queue() scala> fruits ++= List("cherry","cocount") res76: scala.collection.mutable.Queue[String] = Queue(cherry, cocount) scala> fruits ++= List("orange","apple") res77: scala.collection.mutable.Queue[String] = Queue(cherry, cocount, orange, apple) scala> fruits.dequeueFirst(_.startsWith("a")) res79: Option[String] = Some(apple) scala> fruits res80: scala.collection.mutable.Queue[String] = Queue(cherry, cocount, orange) scala> fruits.dequeueAll(_.length > 6) res81: scala.collection.mutable.Seq[String] = ArrayBuffer(cocount) scala> fruits res82: scala.collection.mutable.Queue[String] = Queue(cherry, orange)
2.使用棧
棧是一種后進先出的數據結構。用push方法將元素入棧,用pop方法將元素出棧。
1)創建一個任意數據類型空的可變棧。
scala> import scala.collection.mutable.Stack import scala.collection.mutable.Stack scala> var ints = Stack[Int]() ints: scala.collection.mutable.Stack[Int] = Stack()
2)在創建時給棧初始元素。
scala> val ints = Stack(1,2,3) ints: scala.collection.mutable.Stack[Int] = Stack(1, 2, 3)
3)用push方法向棧中填充元素。
scala> var fruits = Stack[String]() fruits: scala.collection.mutable.Stack[String] = Stack() scala> fruits.push("apple") res2: scala.collection.mutable.Stack[String] = Stack(apple) scala> fruits.push("apple","orange","banana") res3: scala.collection.mutable.Stack[String] = Stack(banana, orange, apple, appl
4)用pop方法將元素出棧。
scala> val next = fruits.pop next: String = banana scala> fruits res4: scala.collection.mutable.Stack[String] = Stack(orange, apple, apple)
5)用top方法查看下一個元素。
scala> fruits.top res5: String = orange scala> fruits res6: scala.collection.mutable.Stack[String] = Stack(orange, apple, apple)
6)用clear清空一個可變棧。
scala> fruits.clear scala> fruits res8: scala.collection.mutable.Stack[String] = Stack()