Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing Stack and Queue in Kotlin (fixed) #1019

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 33 additions & 0 deletions contents/stacks_and_queues/code/kotlin/Queue.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Queue<T> {
private val list = mutableListOf<T>()

fun enqueue(item: T) {
list.add(item)
}

fun dequeue(): T? {
return if (list.isEmpty()) {
null
} else list.removeAt(0)
}

fun front(): T? {
return if (list.isEmpty()) {
null
} else list[0]
}

fun size(): Int = list.size
}

fun main(args: Array<String>) {
val queue = Queue<Int>()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)

println("Front: ${queue.front()}")
println(queue.dequeue())
println("Size: ${queue.size()}")
println(queue.dequeue())
}
33 changes: 33 additions & 0 deletions contents/stacks_and_queues/code/kotlin/Stack.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Stack<T> {
private val list = mutableListOf<T>()

fun push(item: T) {
list.add(item)
}

fun pop(): T? {
return if (list.isEmpty()) {
null
} else list.removeAt(list.size - 1)
}

fun size(): Int = list.size

fun top(): T? {
return if (list.isEmpty()) {
null
} else list[list.size - 1]
}
}

fun main(args: Array<String>) {
val stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)

println("Top: ${stack.top()}")
println(stack.pop())
println("Size: ${stack.size()}")
println(stack.pop())
}
4 changes: 4 additions & 0 deletions contents/stacks_and_queues/stacks_and_queues.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ Here is a simple implementation of a stack:
[import, lang:"rust"](code/rust/Stack.rs)
{% sample lang="python" %}
[import, lang:"python"](code/python/stack.py)
{% sample lang="kotlin" %}
[import, lang:"kotlin"](code/kotlin/Stack.kt)
{% endmethod %}

Here is a simple implementation of a queue:
Expand All @@ -42,6 +44,8 @@ Here is a simple implementation of a queue:
[import, lang:"rust" ](code/rust/Queue.rs)
{% sample lang="python" %}
[import, lang:"python"](code/python/queue.py)
{% sample lang="kotlin" %}
[import, lang:"kotlin"](code/kotlin/Queue.kt)
{% endmethod %}

## License
Expand Down