CircularQueue and test

This commit is contained in:
ivan 2018-12-18 21:46:20 +08:00
parent 2b36d4eb62
commit 7f9d32df0f
2 changed files with 35 additions and 0 deletions

View File

@ -0,0 +1,29 @@
package ch09_queue
import scala.reflect.ClassTag
class CircularQueue[T: ClassTag](capacity: Int) extends DemoQueue[T] {
var items: Array[T] = new Array[T](capacity)
var head = 0
var tail = 0
override def enqueue(data: T): Unit = {
require((tail + 1) % capacity != head, "queue is full")
items(tail) = data
tail = (tail + 1) % capacity
size += 1
}
override def dequeue(): Option[T] = {
if (head == tail) {
None
} else {
size -= 1
val result = Some(items(head))
head = (head + 1) % capacity
result
}
}
}

View File

@ -0,0 +1,6 @@
package ch09_queue
class CircularQueueTest extends DemoQueueTest {
override def getInstance(): DemoQueue[Int] = new CircularQueue[Int](15)
}