diff --git a/contents/stacks_and_queues/code/kotlin/Queue.kt b/contents/stacks_and_queues/code/kotlin/Queue.kt new file mode 100644 index 000000000..08ff48ffc --- /dev/null +++ b/contents/stacks_and_queues/code/kotlin/Queue.kt @@ -0,0 +1,33 @@ +class Queue { + private val list = mutableListOf() + + 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) { + val queue = Queue() + queue.enqueue(1) + queue.enqueue(2) + queue.enqueue(3) + + println("Front: ${queue.front()}") + println(queue.dequeue()) + println("Size: ${queue.size()}") + println(queue.dequeue()) +} \ No newline at end of file diff --git a/contents/stacks_and_queues/code/kotlin/Stack.kt b/contents/stacks_and_queues/code/kotlin/Stack.kt new file mode 100644 index 000000000..ecfb75c3b --- /dev/null +++ b/contents/stacks_and_queues/code/kotlin/Stack.kt @@ -0,0 +1,33 @@ +class Stack { + private val list = mutableListOf() + + 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) { + val stack = Stack() + stack.push(1) + stack.push(2) + stack.push(3) + + println("Top: ${stack.top()}") + println(stack.pop()) + println("Size: ${stack.size()}") + println(stack.pop()) +} \ No newline at end of file diff --git a/contents/stacks_and_queues/stacks_and_queues.md b/contents/stacks_and_queues/stacks_and_queues.md index e63f72a41..8198b5da1 100644 --- a/contents/stacks_and_queues/stacks_and_queues.md +++ b/contents/stacks_and_queues/stacks_and_queues.md @@ -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: @@ -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