-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathExercise_2.kt
More file actions
46 lines (37 loc) · 1003 Bytes
/
Exercise_2.kt
File metadata and controls
46 lines (37 loc) · 1003 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Time Complexity: push() - O(1), pop() - O(1), peek() - O(1), isEmpty() - O(1)
// Space Complexity: O(n) where n = number of elements in the stack
class StackAsLinkedList {
private var root: StackNode? = null
private class StackNode(val data: Int, var next: StackNode? = null)
fun isEmpty(): Boolean {
return root == null
}
fun push(data: Int) {
val newNode = StackNode(data, root)
root = newNode
}
fun pop(): Int {
if (isEmpty()) {
println("Stack Underflow")
return 0
}
val popped = root!!.data
root = root!!.next
return popped
}
fun peek(): Int {
if (isEmpty()) {
println("Stack is empty")
return 0
}
return root!!.data
}
}
fun main() {
val sll = StackAsLinkedList()
sll.push(10)
sll.push(20)
sll.push(30)
println("${sll.pop()} popped from stack")
println("Top element is ${sll.peek()}")
}