Skip to content

Commit 7f9d32d

Browse files
author
ivan
committed
CircularQueue and test
1 parent 2b36d4e commit 7f9d32d

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package ch09_queue
2+
3+
import scala.reflect.ClassTag
4+
5+
class CircularQueue[T: ClassTag](capacity: Int) extends DemoQueue[T] {
6+
7+
var items: Array[T] = new Array[T](capacity)
8+
var head = 0
9+
var tail = 0
10+
11+
12+
override def enqueue(data: T): Unit = {
13+
require((tail + 1) % capacity != head, "queue is full")
14+
items(tail) = data
15+
tail = (tail + 1) % capacity
16+
size += 1
17+
}
18+
19+
override def dequeue(): Option[T] = {
20+
if (head == tail) {
21+
None
22+
} else {
23+
size -= 1
24+
val result = Some(items(head))
25+
head = (head + 1) % capacity
26+
result
27+
}
28+
}
29+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package ch09_queue
2+
3+
class CircularQueueTest extends DemoQueueTest {
4+
5+
override def getInstance(): DemoQueue[Int] = new CircularQueue[Int](15)
6+
}

0 commit comments

Comments
 (0)