Skip to content

Commit 25d75fb

Browse files
authored
Merge pull request #3206 from themlkang42/0155-min-stack-kotlin
Update 0155-min-stack.kt
2 parents e80f705 + 598e394 commit 25d75fb

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

kotlin/0155-min-stack.kt

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
1-
import kotlin.math.min
2-
31
class MinStack() {
4-
private class Node(var `val`: Int, var min: Int, var next: Node?)
5-
6-
private var head: Node? = null
7-
8-
fun push(x: Int) {
9-
if(head==null) head = Node(x,x,null) else head = Node(x, min(x,head?.min!!),head)
2+
private val stack = Stack<Int>()
3+
private val minStack = Stack<Int>()
4+
5+
fun push(`val`: Int) {
6+
val currentMin = if (minStack.isNotEmpty()) minStack.peek() else Integer.MAX_VALUE
7+
val newMin = minOf(currentMin, `val`)
8+
stack.push(`val`)
9+
minStack.push(newMin)
1010
}
1111

1212
fun pop() {
13-
head = head?.next
14-
13+
if (stack.isNotEmpty()) {
14+
stack.pop()
15+
minStack.pop()
16+
}
1517
}
1618

17-
fun top(): Int? {
18-
return head?.`val`
19-
19+
fun top(): Int {
20+
return stack.peek()
2021
}
2122

22-
fun getMin(): Int? {
23-
return head?.min
24-
23+
fun getMin(): Int {
24+
return minStack.peek()
2525
}
26-
2726
}

0 commit comments

Comments
 (0)