Created
December 5, 2017 03:28
-
-
Save YuanLiou/b603a16bb724e44497e049e45df89e1e to your computer and use it in GitHub Desktop.
Queue in Kotlin
This file contains hidden or 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
| class Node { | |
| internal var text: String = "" | |
| internal var nextNode: Node? = null | |
| } |
This file contains hidden or 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
| 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 | |
| } | |
| } |
This file contains hidden or 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
| 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