scala版数据结构----环形队列

前言

       博主发现网上对于scala版本的数据结构代码非常少,甚至有些nc营销号挂着标题复制粘贴别人的python,java代码,也是给我看醉了。
       为了方便学弟学妹们学习(chaozuoye),我准备做一个scala版本数据结构系列,如果觉的有帮助的话,关注下博主呗
class CircleQueue(arrMaxSize: Int) {
  val maxSize: Int = arrMaxSize + 1
  val array: Array[Int] = new Array[Int](maxSize)
  var front: Int = 0 //队头
  var rear: Int = 0 //队尾,指向队尾的下一个节点

  def isEmpty: Boolean = {
    front == rear
  }

  def isFull: Boolean = {
    (rear + 1) % maxSize == front
  }

  def size: Int = {
    (rear + maxSize - front) % maxSize
  }

  def showAllData: Unit = {
    if (isEmpty) {
      println("队列为空")
      return
    }

    for (i <- front until front + size)  {
      var s = array(i % maxSize).toString
      s += " ,"
      println(s"[${i % maxSize}]=$s")
    }

  }

  def add(elem: Int): Unit = {
    if (isFull) {
      println("队列满")
      return
    }
    array(rear) = elem
    rear = (rear + 1) % maxSize
  }

  def nextElem(): Any = {
    if (isEmpty) {
      return new Exception("队列空")
    }
    array(front)
  }

  def get(): Any = {
    if (isEmpty) {
      return new Exception("队列空")
    }
    val value = nextElem().asInstanceOf[Int]
    front = (front + 1) % maxSize
    value
  }

main:

  def main(args: Array[String]): Unit = {
    var circleQueuetmp: Any = null
    Breaks.breakable {
      while (true) {
        val in = StdIn.readLine("输入队列大小:")

        try {
          circleQueuetmp = new CircleQueue(in.toInt)
          Breaks.break
        } catch {
          case ex: Exception => println("请输入正确的数字")
        }
      }
    }
    var queue: CircleQueue = null
    if (circleQueuetmp != null && circleQueuetmp.isInstanceOf[CircleQueue]) {
      queue = circleQueuetmp.asInstanceOf[CircleQueue]
      println("-------")
    }

    var key = ""
    while (true) {
      println("show:显示队列所有数据")
      println("exit:退出")
      println("add:添加")
      println("get:取出数据")
      println("next:显示队头数据")

      key = StdIn.readLine()
      key.trim match {
        case "show" => queue.showAllData
        case "exit" => return
        case "add" => queue.add(StdIn.readInt())
        case "get" => {
          val res = queue.get()
          if (res.isInstanceOf[Exception]) {
            println(res.asInstanceOf[Exception].getMessage)
          } else {
            println(res)
          }
        }
        case "next" => {
          val res = queue.nextElem()
          if (res.isInstanceOf[Exception]) {
            println(res.asInstanceOf[Exception].getMessage)
          } else {
            println(res)
          }
        }
      }
    }

  }

        本博客仅发布于CSDN—一个帅到不能再帅的人 Mr_kidBK。转载请标明出处。
        https://blog.csdn.net/Mr_kidBK

发布了4 篇原创文章 · 获赞 5 · 访问量 2648

猜你喜欢

转载自blog.csdn.net/Mr_kidBK/article/details/105026438
今日推荐