Skip to content

Commit

Permalink
CircularQueue and test
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan committed Dec 18, 2018
1 parent 2b36d4e commit 7f9d32d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
29 changes: 29 additions & 0 deletions scala/src/main/scala/ch09_queue/CircularQueue.scala
Original file line number Diff line number Diff line change
@@ -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 changes: 6 additions & 0 deletions scala/src/test/scala/ch09_queue/CircularQueueTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package ch09_queue

class CircularQueueTest extends DemoQueueTest {

override def getInstance(): DemoQueue[Int] = new CircularQueue[Int](15)
}

0 comments on commit 7f9d32d

Please sign in to comment.