CircularQueue and test
This commit is contained in:
parent
2b36d4eb62
commit
7f9d32df0f
29
scala/src/main/scala/ch09_queue/CircularQueue.scala
Normal file
29
scala/src/main/scala/ch09_queue/CircularQueue.scala
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
6
scala/src/test/scala/ch09_queue/CircularQueueTest.scala
Normal file
6
scala/src/test/scala/ch09_queue/CircularQueueTest.scala
Normal file
@ -0,0 +1,6 @@
|
||||
package ch09_queue
|
||||
|
||||
class CircularQueueTest extends DemoQueueTest {
|
||||
|
||||
override def getInstance(): DemoQueue[Int] = new CircularQueue[Int](15)
|
||||
}
|
Loading…
Reference in New Issue
Block a user