使用數組模擬隊列Scala

這次使用數組模擬隊列

基本思路是使用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)
  }
}

結束

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章