diff --git a/scala/src/main/scala/ch09_queue/CircularQueue.scala b/scala/src/main/scala/ch09_queue/CircularQueue.scala new file mode 100644 index 00000000..cfe77f64 --- /dev/null +++ b/scala/src/main/scala/ch09_queue/CircularQueue.scala @@ -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 + } + } +} diff --git a/scala/src/test/scala/ch09_queue/CircularQueueTest.scala b/scala/src/test/scala/ch09_queue/CircularQueueTest.scala new file mode 100644 index 00000000..a8ea3945 --- /dev/null +++ b/scala/src/test/scala/ch09_queue/CircularQueueTest.scala @@ -0,0 +1,6 @@ +package ch09_queue + +class CircularQueueTest extends DemoQueueTest { + + override def getInstance(): DemoQueue[Int] = new CircularQueue[Int](15) +}