這次使用數(shù)組模擬隊列
基本思路是使用head 和tail的雙指針,當添加時候 tail指針向后移動。彈出隊列頭的時候 head指針向后移動。兩個指針范圍內(nèi)的值就是隊列的內(nèi)容
這次的隊列有缺陷,就是無法重復利用已經(jīng)被使用過的位置匿级。下次我們使用數(shù)組模擬環(huán)形隊列
代碼
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("請輸入一個數(shù)字")
val num = StdIn.readInt()
queue.addQueue(num)
}
case "get"=>{
val res = queue.getQueue()
println(s"取出的數(shù)據(jù)是${res}")
}
case "head" =>{
val res = queue.showHeadQueue()
println(s"頭部的數(shù)據(jù)是${res}")
}
case "exit" => System.exit(0)
}
}
}
}
/**
* 創(chuàng)建一個隊列需要有判斷隊列是否滿,隊列是否空染厅,隊列添加元素痘绎,
* 初始化,彈出元素肖粮,查看隊列內(nèi)容孤页,查看隊列頭
*
* 思路是:
* 使用雙指針,初始化為-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)
}
}
結(jié)束