循环队列
package queue
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag
/**
* Copyright (c) 2019 qingzhi.wu ALL Rights Reserved
*
* Project: arithmetic
* Package: queue
* Version: 1.0
* Created by HeartisTiger on 2019/9/15 16:08
*/
class LoopQueue[E:ClassTag] extends Queue[E] {
private var data = new Array[E](10)
private var front:Int = _
private var tail:Int = _
private var size:Int = _
def this(capacity:Int){
this()
data = new Array[E](capacity + 1)
front = 0
tail = 0
size = 0
}
def getCapacity():Int ={
return data.length -1
}
override def getSize: Int = size
override def isEmpty: Boolean = front == tail
def ifFull():Boolean={
(tail+1)%data.length == front
}
override def enQueue(e: E): Unit = {
if(ifFull()){
//满的 扩容
resize(getCapacity() *2)
}
data(tail) = e
tail = (tail +1) % data.length
size += 1
}
private def resize(newCapacity:Int)={
val newData = new Array[E](newCapacity+1)
for(i <- 0 until size){
newData(i) = data((i + front) % data.length)
}
data = newData
front = 0
tail = size
}
override def deQueue(): E = {
val e = data(front)
front = (front+1) % data.length
size -= 1
return e
}
override def getHead(): E = {
return data(front)
}
def show(): Unit ={
var array = ArrayBuffer[E]()
for(i <- 0 until size){
array.append(data((i+front)%data.length))
}
printf("Size = %d, Pop [%s] Tail \n",getSize,array.mkString(","))
}
}
测试
package queue
/**
* Copyright (c) 2019 qingzhi.wu ALL Rights Reserved
*
* Project: arithmetic
* Package: stack
* Version: 1.0
* Created by HeartisTiger on 2019/9/15 15:26
*/
object Main {
def main(args: Array[String]): Unit = {
val queue = new LoopQueue[Int]()
for(i <- 1 to 20){
queue.enQueue(i)
}
queue.show()
println(queue.deQueue())
println(queue.getHead())
queue.show()
}
}