[LeetCode] 232. Implement Queue using Stacks

[LeetCode] 232. Implement Queue using Stacks

Kotlin

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
class MyQueue() {

/** Initialize your data structure here. */
val input = Stack<Int>()
val output = Stack<Int>()

/** Push element x to the back of queue. */
fun push(x: Int) {
input.push(x)
}

/** Removes the element from in front of queue and returns that element. */
fun pop(): Int {
peek()
return output.pop()
}

/** Get the front element. */
fun peek(): Int {
if (output.isEmpty()) {
while(input.isNotEmpty()) {
output.push(input.pop())
}
}
return output.peek()
}

/** Returns whether the queue is empty. */
fun empty(): Boolean {
return input.isEmpty() && output.isEmpty()
}
}
1
2
Runtime: 168 ms, faster than 26.03% of Kotlin online submissions for Implement Queue using Stacks.
Memory Usage: 35.4 MB, less than 100.00% of Kotlin online submissions for Implement Queue using Stacks.

댓글