2-环形队列-Scala实现
这里选择用数组实现,为了队列可以复用,选择环形数组实现
import scala.io.StdIn object CircleArrayQueue { def main(args: Array[String]): Unit = { val queue = new ArrayQueue2(3) //菜单演示 var key = "" while (true){ println() println("请选择菜单") println("show:显示队列") println("add:添加数据") println("get:获取数据") println("peek:获取队列头元素") println("exit:退出程序") key = StdIn.readLine() key match { case "show" => queue.show() case "add" => println("请输入一个数") val num=StdIn.readInt() queue.addQueue(num) case "get" => //查看头元素判断 val res: Any = queue.getQueue() if (res.isInstanceOf[Exception]){ println(res.asInstanceOf[Exception].getMessage) }else{ println("队列取出的值为:"+res) } case "peek" => val res: Any = queue.peek() if (res.isInstanceOf[Exception]){ println(res.asInstanceOf[Exception].getMessage) }else{ println("当前队列头元素为:"+res) } } } } } class ArrayQueue2(arrMaxSize:Int){ val maxSize =arrMaxSize //指定队列大小 val arr = new Array[Int](maxSize) //队列中数据,存放在数组中 var front = 0 //初始化为0,表示队列的头,指向队列的第一个元素 var rear = 0 //初始化0,指向队列最后一个元素的后一个位置 //判断是否满了 def isFull():Boolean ={ (rear+1) % maxSize == front } //判断队列是否空 def isEmpty():Boolean={ rear == front } //添加数据 def addQueue(num : Int): Unit={ if (isFull()){ println("队列满了,不能加入了") return } arr(rear) =num //将rear 后移 rear =(rear+1) % maxSize } //遍历显示队列 //1.从front开始打印,打印多少个元素 //2.需要统计出该队列有多少个有效元素 def show(): Unit ={ if (isEmpty()){ println("队列空~") return } for (i <- front until front+size()){ printf("arr(%d)=%d \t",(i % maxSize),arr(i % maxSize)) } } def size():Int={ return (rear + maxSize -front) % maxSize } //取数据,可能取到数据也可能取不到数据(异常) def getQueue():Any={ if(isEmpty()){ return new Exception("队列空,没有数据") } //因为front指向队列的第一个元素 val res = arr(front) front = (front+1) % maxSize return res } //查看队列的头元素但是不取出 def peek():Any={ if (isEmpty()){ return new Exception("队列空,无数据") } return arr(front) } }
相关推荐
匆匆那些年 2020-10-15
TheBigBlue 2020-07-28
shenwenjie 2020-07-07
muhongdi 2020-07-07
waitwolf 2020-07-08
yunfenglee 2020-07-08
yunfenglee 2020-07-08
kekeromer 2020-07-08
匆匆那些年 2020-07-07
liqinglin0 2020-07-05
TheBigBlue 2020-07-05
kekeromer 2020-06-13
zhixingheyitian 2020-06-08
TheBigBlue 2020-06-06
liqinglin0 2020-06-01
liqinglin0 2020-06-01
yunfenglee 2020-05-30
MICKEYSTUDY 2020-05-28
muhongdi 2020-05-19