📜  Scala队列

📅  最后修改于: 2021-01-09 12:11:22             🧑  作者: Mango

Scala队列

队列实现了一种数据结构,该结构允许以先进先出(FIFO)的方式插入和检索元素。

在scala中,Queue被实现为一对列表。一种用于插入元素,第二种用于包含已删除的元素。元素将添加到第一个列表中,并从第二个列表中删除。

Scala队列示例

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var queue = Queue(1,5,6,2,3,9,5,2,5)
        var queue2:Queue[Int] = Queue(1,5,6,2,3,9,5,2,5)
        println(queue)  
        println(queue2)
    }
}

输出:

Queue(1, 5, 6, 2, 3, 9, 5, 2, 5)
Queue(1, 5, 6, 2, 3, 9, 5, 2, 5)

Scala队列示例2

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var queue = Queue(1,5,6,2,3,9,5,2,5)
        print("Queue Elements: ")
        queue.foreach((element:Int)=>print(element+" "))  
        var firstElement = queue.front
        print("\nFirst element in the queue: "+ firstElement)       
        var enqueueQueue = queue.enqueue(100)
        print("\nElement added in the queue: ")
        enqueueQueue.foreach((element:Int)=>print(element+" "))
        var dequeueQueue = queue.dequeue
        print("\nElement deleted from this queue: "+ dequeueQueue)
    }
}

输出:

Queue Elements: 1 5 6 2 3 9 5 2 5 
First element in the queue: 1
Element added in the queue: 1 5 6 2 3 9 5 2 5 100 
Element deleted from this queue: (1,Queue(5, 6, 2, 3, 9, 5, 2, 5))