forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
ivan
committed
Dec 18, 2018
1 parent
2b36d4e
commit 7f9d32d
Showing
2 changed files
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |