Skip to content

Instantly share code, notes, and snippets.

@YuanLiou
Created December 5, 2017 03:28
Show Gist options
  • Select an option

  • Save YuanLiou/b603a16bb724e44497e049e45df89e1e to your computer and use it in GitHub Desktop.

Select an option

Save YuanLiou/b603a16bb724e44497e049e45df89e1e to your computer and use it in GitHub Desktop.
Queue in Kotlin
class Node {
internal var text: String = ""
internal var nextNode: Node? = null
}
class Queue {
var head: Node? = null
var tail: Node? = null
fun dequeue(): String? {
val result: String? = head?.text
head = head?.nextNode
if (head == null) {
tail = head // empty
}
return result
}
fun enqueue(value: String) {
var newNode = Node()
newNode.text = value
if (tail != null) {
tail!!.nextNode = newNode
tail = newNode
} else {
// first node
tail = newNode
head = tail
}
}
fun isEmpty(): Boolean {
return tail == null
}
fun size(): Int {
var size: Int = 0
var node = head
while (node != null) {
size++
node = node.nextNode
}
return size
}
}
fun main(argv: Array<String>) {
val queue = Queue()
// queue.dequeue()
checkSize(queue)
queue.enqueue("Jerry")
checkSize(queue)
queue.dequeue()
checkSize(queue)
queue.enqueue("Steve")
queue.enqueue("Norlen")
queue.enqueue("Jacky")
queue.enqueue("Lois")
queue.enqueue("Bruce")
for (i in queue.size() downTo 1) {
println("dequeue result = " + queue.dequeue())
}
}
fun checkSize(queue: Queue) {
println("Size is = " + queue.size())
println("Queue is Empty? = " + queue.isEmpty())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment