用数组实现队列-scala语言描述

一、用数组实现队列-scala语言描述

import scala.io.StdIn

/**
 * ClassName:Queue
 * Package:datastructer
 */
object ArrayQueue {
  def main(args: Array[String]): Unit = {
    val queue = new ArrayQueue(3)
    var key = ""
    while (true) {
      println()
      println("请选择菜单")
      println("show:显示队列")
      println("add:添加数据")
      println("get:获取数据")
      println("exit:退出程序")
      key = StdIn.readLine()
      key match {
        case "show" => queue.show()
        case "add" =>
          println("请输入一个数字")
          val num = StdIn.readInt()
          queue.inQueue(num)
        case "get" =>
          val res = queue.outQueue()
        case "exit" =>
          System.exit(0)
      }
    }

  }


}

class ArrayQueue(arrMaxSize: Int) {
  val maxSize = arrMaxSize
  val arr = new Array[Int](maxSize)
  // 队列首 不包含第一个元素
  var front = -1
  // 队列尾 包含第一个元素
  var tear = -1

  def isFull(): Boolean = {
    tear == maxSize - 1
  }

  def isEmpty(): Boolean = {
    front == tear
  }

  // 向队列添加元素
  def inQueue(node: Int): Unit = {
    if (isFull) {
      println("队列已满,无法加入")
      return
    }
    tear += 1
    arr(tear) = node
  }

  // 出队列
  def outQueue() = {
    if (isEmpty) {
      new Exception("队列空,无数据")
    }
    front += 1
    arr(front)
  }

  // 遍历显示队列
  def show(): Unit = {
    if (isEmpty) {
      println("队列为空,无数据。")
    }
    println("队列数据情况是:")
    for (i <- front + 1 to tear) {
      printf("arr(%d)=%d \t", i, arr(i))
    }
  }

  // 获取元素
  def get(index: Int): Int = {
    if (index < front + 1 || index > tear) {
      println("下标越界")
      return -1
    }
    arr(index)
  }

  // 修改元素
  def update(index: Int, newNum: Int): Unit = {
    if (index < front + 1 || index > tear) {
      println("下标越界")
      return -1
    }
    arr(index) = newNum
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值