class Queue<T> {
class Node<T>(v: T) {
val value: T = v
var next: Node<T>? = null
}
var head: Node<T>? = null
var length: Int = 0
private set
fun enqueue(v: T) {
var newNode = Node<T>(v)
if (head == null) {
head = newNode
} else {
var current: Node<T> = head ?: return // can't be null
while (current.next != null) {
current = current.next ?: return // can't be null
}
current.next = newNode
}
length++
}
fun dequeue(): T? {
val dequeuer = head ?: return null
// immutable shadow
val retval: T = dequeuer.value
head = dequeuer.next
length--
return retval
}
fun isEmpty(): Boolean = length == 0
fun print() {
var current: Node<T>? = head
print ("[")
while (current != null) {
print(current.value)
current = current.next
if (current != null) print(", ")
}
println("]")
}
}
Comments
0 B
|👍
/👎
0 B
|👍
/👎