Skip to content

Commit b211778

Browse files
committed
Stacks and Queues in Kotlin!
1 parent c3311b6 commit b211778

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Queue<T> {
2+
private val list = mutableListOf<T>()
3+
4+
fun enqueue(item: T) {
5+
list.add(item)
6+
}
7+
8+
fun dequeue(): T? {
9+
return if (list.isEmpty()) {
10+
null
11+
} else list.removeAt(0)
12+
}
13+
14+
fun front(): T? {
15+
return if (list.isEmpty()) {
16+
null
17+
} else list[0]
18+
}
19+
20+
fun size(): Int = return list.size
21+
}
22+
23+
fun main(args: Array<String>) {
24+
val queue = Queue<Int>()
25+
queue.enqueue(1)
26+
queue.enqueue(2)
27+
queue.enqueue(3)
28+
29+
println("Front: ${queue.front()}")
30+
println(queue.dequeue())
31+
println("Size: ${queue.size()}")
32+
println(queue.dequeue())
33+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Stack<T> {
2+
private val stack = mutableListOf<T>()
3+
4+
fun push(item: T) {
5+
stack.add(item)
6+
}
7+
8+
fun pop(): T? {
9+
return if (stack.isEmpty()) {
10+
null
11+
} else stack.removeAt(stack.size - 1)
12+
}
13+
14+
fun size(): Int = return stack.size
15+
16+
fun top(): T? {
17+
return if (stack.isEmpty()) {
18+
null
19+
} else stack[stack.size - 1]
20+
}
21+
}
22+
23+
fun main(args: Array<String>) {
24+
val stack = Stack<Int>()
25+
stack.push(1)
26+
stack.push(2)
27+
stack.push(3)
28+
29+
println("Top: ${stack.top()}")
30+
println(stack.pop())
31+
println("Size: ${stack.size()}")
32+
println(stack.pop())
33+
}

contents/stacks_and_queues/stacks_and_queues.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ Here is a simple implementation of a stack:
2828
[import, lang:"rust"](code/rust/Stack.rs)
2929
{% sample lang="python" %}
3030
[import, lang:"python"](code/python/stack.py)
31+
{% sample lang="kotlin" %}
32+
[import, lang:"kotlin"](code/kotlin/Stack.kt)
3133
{% endmethod %}
3234

3335
Here is a simple implementation of a queue:
@@ -42,6 +44,8 @@ Here is a simple implementation of a queue:
4244
[import, lang:"rust" ](code/rust/Queue.rs)
4345
{% sample lang="python" %}
4446
[import, lang:"python"](code/python/queue.py)
47+
{% sample lang="kotlin" %}
48+
[import, lang:"kotlin"](code/kotlin/Queue.kt)
4549
{% endmethod %}
4650

4751
## License

0 commit comments

Comments
 (0)