使用数组模拟队列Scala

本文介绍如何使用数组在Scala中模拟队列,通过head和tail双指针操作,详细阐述了添加元素时tail指针后移以及弹出队列头时head指针后移的逻辑。虽然此实现无法重复利用已使用位置,但为后续的环形队列模拟奠定了基础。
摘要由CSDN通过智能技术生成

这次使用数组模拟队列

基本思路是使用head 和tail的双指针,当添加时候 tail指针向后移动。弹出队列头的时候 head指针向后移动。两个指针范围内的值就是队列的内容

这次的队列有缺陷,就是无法重复利用已经被使用过的位置。下次我们使用数组模拟环形队列

代码

package cn.xipenhui.chapter1

import scala.io.StdIn

object ArrayQueueDemo {


  def main(args: Array[String]): Unit = {
    val queue = new ArrayQueue(3)

    //控制台输出的代码
    var key = ""
    while (true){
      println("show : 显示队列")
      println("exit 退出队列")
      println("add 添加元素")
      println("get 取出元素")
      println("head 查看队列头")

      key = StdIn.readLine()
      key match {
        case "show"=> queue.showQueue()
        case "add" =>{
          println("请输入一个数字")
          val num = StdIn.readInt()
          queue.addQueue(num)
        }
        case "get"=>{
          val res = queue.getQueue()
            println(s"取出的数据是${res}")
        }
        case "head" =>{
          val res = queue.showHeadQueue()

            println(s"头部的数据是${res}")

        }
        case "exit" => System.exit(0)
      }
    }
  }

}

/**
 * 创建一个队列需要有判断队列是否满,队列是否空,队列添加元素,
 * 初始化,弹出元素,查看队列内容,查看队列头
 *
 * 思路是:
 *   使用双指针,初始化为-1
 *   添加元素时候,先移动尾部指针,再复制
 *   弹出元素的时候,先移动指针,再弹出元素 因为 head指向的是当前头的前一位,需要移动到当前,再弹出
 */
class ArrayQueue(arrMaxSize:Int){

  val maxSize = arrMaxSize
  val arr = new Array[Int](maxSize)
  var head = -1
  var tail = -1

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

  def isEmpty={
    head == tail
  }

  def addQueue(num:Int)={
    if(isFull()){
      throw  new RuntimeException("queue is full, cann't add element")
    }
    tail += 1
    arr(tail) = num
  }

  def getQueue() ={
    if(isEmpty){
      throw  new RuntimeException("queue is empty, cann't get element")
    }
    head += 1
    arr(head)
  }

  def showQueue(): Unit ={
    if(isEmpty){
      throw  new RuntimeException("queue is empty, cann't get element")
    }
    for (i <- head+1 to tail){
      println(s"arr(${i}) = ${arr(i)}")
    }
  }

  def showHeadQueue() ={
    if(isEmpty){
      throw  new RuntimeException("queue is empty, cann't get element")
    }
    arr(head+1)
  }
}

结束

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值