Created
August 1, 2017 16:53
-
-
Save AndyBowes/d632f80ed38a29ca56f3c59280f153a9 to your computer and use it in GitHub Desktop.
Kotlin Queue Implementation
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<T> { | |
val elements: MutableList<T> = mutableListOf() | |
fun isEmpty() = elements.isEmpty() | |
fun count() = elements.size | |
fun enqueue(item: T) = elements.add(item) | |
fun dequeue() = if (!isEmpty()) elements.removeAt(0) else null | |
fun peek() = if (!isEmpty()) elements[0] else null | |
override fun toString(): String = elements.toString() | |
} | |
fun <T> Queue<T>.push(items: Collection<T>) = items.forEach { this.enqueue(it) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I used this snippet to solve some problems on Leetcode but than I found that
LinkedList
ArrayDeque
is better 💃Anyway, I really appreciate your gist. 💯 💯