File tree Expand file tree Collapse file tree 3 files changed +70
-0
lines changed
contents/stacks_and_queues Expand file tree Collapse file tree 3 files changed +70
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change @@ -28,6 +28,8 @@ Here is a simple implementation of a stack:
28
28
[ import, lang:"rust"] ( code/rust/Stack.rs )
29
29
{% sample lang="python" %}
30
30
[ import, lang:"python"] ( code/python/stack.py )
31
+ {% sample lang="kotlin" %}
32
+ [ import, lang:"kotlin"] ( code/kotlin/Stack.kt )
31
33
{% endmethod %}
32
34
33
35
Here is a simple implementation of a queue:
@@ -42,6 +44,8 @@ Here is a simple implementation of a queue:
42
44
[ import, lang:"rust" ] ( code/rust/Queue.rs )
43
45
{% sample lang="python" %}
44
46
[ import, lang:"python"] ( code/python/queue.py )
47
+ {% sample lang="kotlin" %}
48
+ [ import, lang:"kotlin"] ( code/kotlin/Queue.kt )
45
49
{% endmethod %}
46
50
47
51
## License
You can’t perform that action at this time.
0 commit comments